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 需求DC-DC降压电路
  • ¥15 java corba的客户端该如何指定使用本地某个固定IP去连接服务端?
  • ¥15 activiti工作流问题,求解答
  • ¥15 有人写过RPA后台管理系统么?
  • ¥15 Bioage计算生物学年龄
  • ¥20 如何将FPGA Alveo U50恢复原来出厂设置哇?
  • ¥50 cocos2d-x lua 在mac上接入lua protobuf?
  • ¥15 es 7.17.20版本生成时间戳
  • ¥15 wpf dategrid表头排序图标自定义
  • ¥15 xshell无法连接提示ssh服务器拒绝密码