dongzhan2029 2014-10-12 00:15
浏览 159
已采纳

当有空格时,preg_match_all正则表达式失败

I'm trying to get the image urls from html source code using the following regex, but it fails when the image url has spaces in it. For example this url:

<img src="http://a57.foxnews.com/global.fncstatic.com/static/managed/img/Entertainment/876/493/kazantsev pink bikini reuters.jpg?ve=1&amp;tl=1" alt="kazantsev pink bikini reuters.jpg" itemprop="image">

$image_regex_src_url = '/<img[^>]*'.'src=[\"|\'](.*)[\"|\']/Ui';
preg_match_all($image_regex_src_url, $string, $out, PREG_PATTERN_ORDER);

This gives me back the following.
http://a57.foxnews.com/global.fncstatic.com/static/managed/img/Entertainment/876/493/kazantsev

Is there a way to match any character including whitespace? Or is it something I have to set in the php configuration?

  • 写回答

1条回答 默认 最新

  • donglu1973 2014-10-12 00:31
    关注

    You have several issues with your regular expression.

    First, you are trying to use the concatenation operator ('.') to join both parts of your expression together ( this is not necessary ). Secondly, you don't need to use the alternation operator | inside of your character classes.

    The dot . will match any character except newline sequence. It is a possibility that these tags could possibly include line breaks since they are located in HTML source. You could use the s (dotall) modifier which forces the dot to match any character including line breaks or use a negated character class meaning match any character except.

    Using the s (dotall) modifier:

    $image_regex_src_url = '/<img[^>]*src=(["\'])(.*?)\1/si';
    

    Using a negated character class [^ ]

    $image_regex_src_url = '/<img[^>]*src=(["\'])([^"\']*)\1/i';
    

    Although, it is much easier to use a parser such as DOM to grab the results.

    $doc = new DOMDocument;
    @$doc->loadHTML($html); // load the HTML
    
    foreach($doc->getElementsByTagName('img') as $node) {
       $urls[] = $node->getAttribute('src');
    }
    
    print_r($urls);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵