dongshi1914 2010-12-06 11:56
浏览 21
已采纳

php正则表达式preg_replace

I have following code (php), it will match img-src and replace with new 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);

For images that have src as "http://www.example.com/a.jpg", there is no issue, but for images that have src that contains query string like "http://www.example.com/b.jpg?height=900", it's not matching

I want to match images with and without query string.

  • 写回答

1条回答 默认 最新

  • du77887 2010-12-06 12:02
    关注

    You can use PHP's preg_quote()-function instead of str_replace(). It automatically escapes all regular expression special characters (see the docs). That should solve the problem, since your str_replace()-solution did not escape ?, which is a special character in regular expressions:

    $match_pattern = '/<img[^<]*src\s*=\s*\"'.preg_quote($source_url, '/').'\"[^>]*>/iUu';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有人会SIRIUS 5.8.0这个软件吗
  • ¥30 comsol仿真等离激元
  • ¥15 静电纺丝煅烧后如何得到柔性纤维
  • ¥15 (标签-react native|关键词-镜像源)
  • ¥100 照片生成3D人脸视频
  • ¥15 伪装视频时长问题修改MP4的时长问题,
  • ¥15 JETSON NANO
  • ¥15 VS开发qt时如何在paintgl函数中用pushbutton控制切换纹理
  • ¥20 关于 openpyxl 处理excel文件地问题
  • ¥15 MS中不知道高分子的构型怎么构建模型