dongsu7049 2012-10-02 06:23
浏览 36
已采纳

preg_match多个来源

How do I exactly match multiple instances of img tags? I read up a few tutorials on preg_match yet never really quite understand.

I have this as my base:

<img src="http://example.com/1.png" alt="Example" />

<img class="Class" src="http://example.com/2.jpg" alt="Example 2" />

And I did up a small like regex:

<img (src="|class="Class" src=")http://.+\.(?:jpe?g|png)" alt="

After this, I'm stuck. How do I continue to match all till the end of the both strings?

I found out about the array part on PHP website itself:

preg_match('@^(?:http://)?([^/]+)@i',
    "http://www.php.net/index.html", $matches);
$host = $matches[1];

Using my code, how do I get the image URL, and the alt tag?

Thanks!

  • 写回答

2条回答 默认 最新

  • dtds8802 2012-10-02 06:35
    关注

    For the original question, use preg_match_all() function to get all the matches.

    For the second question ("Using my code, how do I get the image URL, and the alt tag?"), basically your regex is correct. However, I would suggest to get the whole <img> tag first, then do another preg_match() to get the href and alt attributes, since their order may vary.

    $html = "<img src='test.jpg' alt='aaaaaaaaaaa!'>  adfa <img src='test2.jpg' alt='aaaaaaaaaaa2'>  ";
    
    $pattern = '/<img\s[^>]*>/';
    $count = preg_match_all($pattern, $html, $matches, PREG_SET_ORDER);
    
    echo "Found: " . $count . "
    ";
    if ($count > 0) {
        foreach ($matches as $match) {
            $img = $match[0];
            echo "img: " . $img . "
    ";
            if (preg_match("/src=['\"]([^'\"]*)['\"]/", $img, $val)) {  # UPDATE: use () to catch the content of src
                $src = $val[1];      # UPDATE: get the part in ()
            }
            if (preg_match("/alt=['\"]([^'\"]*)['\"]/", $img, $val)) {   # UPDATE
                $alt = $val[1];      # UPDATE
            }
    
            echo "src = " . $src . ", alt = " . $alt . "
    ";
        }
    }
    

    UPDATE

    Answer to your comment. Sure. Just use a group to catch the part after src=. I updated the source above and commented with "UPDATE".

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证