duanben1909 2012-09-16 21:38
浏览 105
已采纳

使用preg_match_all从字符串中提取Image SRC

I have a string of data that is set as $content, an example of this data is as follows

This is some sample data which is going to contain an image in the format <img src="http://www.randomdomain.com/randomfolder/randomimagename.jpg">.  It will also contain lots of other text and maybe another image or two.

I am trying to grab just the <img src="http://www.randomdomain.com/randomfolder/randomimagename.jpg"> and save it as another string for example $extracted_image

I have this so far....

if( preg_match_all( '/<img[^>]+src\s*=\s*["\']?([^"\' ]+)[^>]*>/', $content, $extracted_image ) ) {
$new_content .= 'NEW CONTENT IS '.$extracted_image.'';

All it is returning is...

NEW CONTENT IS Array

I realise my attempt is probably completly wrong but can someone tell me where I am going wrong?

  • 写回答

3条回答 默认 最新

  • dongqian5639 2018-11-16 23:21
    关注

    Using regex to parse valid html is ill-advised. Because there can be unexpected attributes before the src attribute, because non-img tags can trick the regular expression into false-positive matching, and because attribute values can be quoted with single or double quotes, you should use a dom parser. It is clean, reliable, and easy to read.

    Code: (Demo)

    $string = <<<HTML
    This is some sample data which is going to contain an image
    in the format <img src="http://www.randomdomain.com/randomfolder/randomimagename.jpg">.
    It will also contain lots of other text and maybe another image or two
    like this: <img alt='another image' src='http://www.example.com/randomfolder/randomimagename.jpg'>
    HTML;
    
    $srcs = [];
    $dom=new DOMDocument;
    $dom->loadHTML($string);
    foreach ($dom->getElementsByTagName('img') as $img) {
        $srcs[] = $img->getAttribute('src');
    }
    
    var_export($srcs);
    

    Output:

    array (
      0 => 'http://www.randomdomain.com/randomfolder/randomimagename.jpg',
      1 => 'http://www.example.com/randomfolder/randomimagename.jpg',
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 使用Java milo连接Kepserver服务端报错?
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?
  • ¥20 软件开发方法学习来了
  • ¥15 微信小程序商城如何实现多商户收款 平台分润抽成