开发者

PHP Regex exact url match, change img src

I have a HTML document with some images in tags. I would like to change each img sources (src) with different, defined in array, value.

When I run the following code I get

Warning: preg_replace(): Unknown modifier '/' in /var/www/test.php on line 9
Warning: preg_replace(): Unknown modifier '/' in /var/www/test.php on line 9

How do I escape the url strings correctly?

<?php
$body = "<img src=http://www.google.com/img1.jpg><br>"
      + "<img width=300 src=http://www.bbc.co.uk/img1.jpg>";

$changes = array();
$changes[] = array('from' => 'http://www.google.com/img1.jpg',
                     'to' => 'http://cnn.com/image2.jpg');
$changes[] = array('from' => 'http://www.bbc.co.uk/img1.jpg',
    开发者_如何学C                 'to' => 'http://www.foo.bar.com/image2.jpg');

foreach ($changes as $change){
    $body = preg_replace('/<(img.*src)="'.$change['from'].'".*\/?>/',
                         '<\1="'.$change['to'].'">', $body)
            . PHP_EOL;
}
?>


Try this:

http://php.net/manual/en/function.urlencode.php for encoding urls.

However, it looks like you're just trying to replace a part of the string in $body, so I'd use

http://php.net/manual/en/function.str-replace.php

instead of your regular expression.

<?php
$body = "<img src=http://www.google.com/img1.jpg><br><img width=300 src=http://www.bbc.co.uk/img1.jpg>";

$changes = array();
$changes[] = array('from' => 'http://www.google.com/img1.jpg', 'to'=> 'http://cnn.com/image2.jpg');
$changes[] = array('from' => 'http://www.bbc.co.uk/img1.jpg', 'to' => 'http://www.foo.bar.com/image2.jpg');

foreach ($changes as $change){
$body = str_replace($change['from'],$change['to'],$body);
}
?>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜