开发者

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

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

Example:

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

to

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

I didn't find a soultion with preg开发者_运维问答_replace, but it may be a simple regexp line. Thanks!

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 can't use urlencode here as it encodes the other stuff as well.


EDIT

I may have missed the point, if you are not scanning over already written out HTML, this probably is not for you. This is for if you were scrapping it for whatever reason. I am leaving it up for pure nostalgia as it could help someone else who wants to scrape and replace. Sorry for the confusion.


Since you know the tags and the attribute, I would suggest looking into the PHP DOM to do this. Regex can do it, but the DOM would be preferred and perhaps bit easier / more reliable, given the context you are looking at. This will scan the generated HTML and allow you to replace items inside of attributes (in this case src) that with using the rawurlencode() you can get the spaces converted to %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();

Worked on my small test file, just an example of how it could be done :)


The space is represented by a %20 in the url but there are other chars that you might want to have converted for other images so you should use the general urlencode function instead of using a "simple regex" as stated in the OP.

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


this is what you need rawurlencode();

php.net/rawurlencode


Hey, I've found a simple solution, using preg_replace_callback. I've never heard of this function before, but it's great.

Posting the code here:

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

Thanks for all the replies.


Something like the following may work:

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

But it's a bit hard to tell since you didn't give us any details about why preg_replace didn't work, what its output was, etc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜