php正则表达式preg_replace

时间:2010-12-06 11:56:02

标签: php regex

我有以下代码(php),它将匹配img-src并替换为新的url

$rep = array('/', '+', '(', ')');
$with = array('\/', '\+', '\(', '\)');

$match_pattern = '/<img[^<]*src\s*=\s*\"'.str_replace($rep, $with, $source_url).'\"[^>]*>/iUu';
$img_replace_str = '<img src="'.$new_url.'" />';
$post_content = preg_replace($match_pattern, $img_replace_str, $post_content);

对于src为“http://www.example.com/a.jpg”的图片,没有问题,但对于src包含查询字符串的图像,如“http://www.example。 com / b.jpg?height = 900“,它不匹配

我希望使用和不使用查询字符串来匹配图像。

1 个答案:

答案 0 :(得分:2)

您可以使用PHP的preg_quote()-function代替str_replace()。它会自动转义所有正则表达式特殊字符(请参阅文档)。这应该可以解决问题,因为你的str_replace() - 解决方案没有逃脱?,这是正则表达式中的一个特殊字符:

$match_pattern = '/<img[^<]*src\s*=\s*\"'.preg_quote($source_url, '/').'\"[^>]*>/iUu';