How to replace spaces with% 20 in <img> tags

I would like to replace all the spaces in the image tags of the html text.

Example:

<img src="photo 1.jpg" />

to

<img src="photo%201.jpg"/>

I did not find soultion with preg_replace, but it could be a simple regex string. Thank!

Edit : Sorry guys, my description was not very clear. So, I have a full html page , and I only want to replace inside the img tags. I cannot use urlencode here, as it encodes other things as well.

+3
source share
5 answers

URL- %20, , , urlencode " ", OP.

<img src="<?php echo urlencode('file name.jpg'); ?>"/>
+5

, , HTML, , , . , - . , -, . .


, PHP DOM . Regex , DOM , , /, , . HTML ( src), rawurlencode() %20.

<?php
$dom = new DOMDocument();
// $dom->load('test.html'); // if in a file
$dom->loadHTML($html); // if in a string

for ($i=0; $i<$dom->getElementsByTagName('img')->length; $i++) {
    $encoded = implode("/", array_map("rawurlencode",
         explode("/", $dom->getElementsByTagName('img')
                    ->item($i)->getAttribute('src'))));

    $dom->getElementsByTagName('img')
            ->item($i)
            ->setAttribute('src',$encoded);
}


echo $dom->saveHTML();

, , :)

+7

rawurlencode();

php.net/rawurlencode

+4

, , preg_replace_callback. , .

:

$text = preg_replace_callback("/src=[\'\"](.*?)[\'\"]/", "removeSpaces", $text);
function removeSpaces($matches) {
  return "src='" . str_replace(" ", "%20", $matches[1]) . "'";
}

.

+2

:

$img_src = 'images/some crazy image.jpg';
$img_src = preg_replace('/ /g', '%20', $img_src);
echo '<img src="' . $img_src . '" alt="some image" />';

But this is a little difficult to say, since you did not give us any details about why it preg_replacedid not work, what was its conclusion, etc.

+1
source

All Articles