【问题标题】:Regular expression to find "src" attribute of HTML "img" element in PHP在 PHP 中查找 HTML“img”元素的“src”属性的正则表达式
【发布时间】:2013-06-14 09:03:14
【问题描述】:

我有一个字符串,里面有一个图像:

"<p><img src="http://yahoo.com/testfolder/userdata/editoruploadimages/confused man.jpg" /></p>"

我无法使用正则表达式获取图像 URL。我的代码是:

preg_match_all("/src=([^\\s]+)/", $questArr_str, $images);

此代码在遇到图像名称中的空格时停止执行。它只返回"http://yahoo.com/testfolder/userdata/editoruploadimages/confused

返回的字符串应该是: "http://yahoo.com/testfolder/userdata/editoruploadimages/confused man.jpg"

【问题讨论】:

  • 您只在正则表达式中搜索非空白字符,为什么要匹配空格?正则表达式不是匹配 html 的最佳解决方案,最好使用 html/dom 解析器。

标签: php html regex


【解决方案1】:

读取([^\s]+) 的部分表示选择任何不是空格的内容。

也许可以试试:

/src="([^"]+)"/

选择不是双引号的任何内容。

【讨论】:

    【解决方案2】:

    我会抓住引号内的所有内容:

    preg_match_all('/src="([^"]+)"/', $questArr_str, $images);
    

    【讨论】:

    • 只匹配第一个模式。
    • preg_match_all "搜索所有匹配项" – 你不需要g 标志
    【解决方案3】:

    感谢每一位帮助我的人。

    我通过以下方式找到了我的解决方案:

    pattern = "/src=([^\\\"]+)/"
    

    【讨论】:

      【解决方案4】:

      这是一个简单的方法来匹配&lt;img /&gt;标签src属性或html/PHP中的内容与正则表达式。

      示例:

      <img class="img img-responsive" title="publisher.PNG" src="media/projectx/agent/author/post/2/image/publisher.PNG" alt="" width="80%" />
      

      仅匹配 src 属性内容使用

      preg_match("%(?<=src=\")([^\"])+(png|jpg|gif)%i",$input,$result)
      

      $result[0] 将输出media/projectx/agent/author/post/2/image/publisher.PNG

      要匹配 `src' 属性及其内容,请使用

      preg_match("%src=\"([^\"])+(png|jpg|gif)\"%i",$input,$result)
      

      $result[0] 将输出src="media/projectx/agent/author/post/2/image/publisher.PNG"

      【讨论】:

        猜你喜欢
        • 2015-11-08
        • 1970-01-01
        • 2012-05-26
        • 1970-01-01
        • 2023-03-09
        • 2011-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多