【问题标题】:php regular expression preg_replacephp 正则表达式 preg_replace
【发布时间】:2011-05-20 22:47:25
【问题描述】:

我有以下代码(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",不匹配

我想匹配带有和不带有查询字符串的图像。

【问题讨论】:

标签: php regex


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-11
    • 2011-04-11
    • 1970-01-01
    相关资源
    最近更新 更多