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 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题