【问题标题】:How to extract image src url omitting the "?" and query string?如何提取图像 src url 省略“?”和查询字符串?
【发布时间】:2016-02-05 08:26:52
【问题描述】:

我使用以下正则表达式来获取 img-Tag 的 url:

$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post_single->post_content, $matches);

但是,$matches 给了我以下结果:

http://example.com/wp-content/uploads/2013/11/dsc_842.jpg

->这很好。

http://example.com/wp-content/uploads/2013/11/dsc_0546.jpg?w=640

-> 这不好。

如何更改正则表达式以防止?w=640 包含在我的结果中?

非常感谢您的帮助。

谢谢!

【问题讨论】:

  • '/&lt;img.+src=[\'"]([^?\'"]+)/i'
  • 只是把我的两分钱放进去:当您使用 Wordpress(在 PHP 上)时,您也可以使用函数 parse_url(),它能够开箱即用地处理您的所有需求.

标签: php regex wordpress url preg-match-all


【解决方案1】:

很容易变成这样:

$output = preg_match_all('/<img.+src=[\'"]([^\'"?]+)[\'"?].*>/i', $post_single->post_content, $matches);

这样([^\'"?]+)[\'"?]首先匹配引号和问号之外的任何内容,然后需要一个。

例如:https://regex101.com/r/yJ1yA1/1

【讨论】:

    【解决方案2】:

    我想提出另一种方法(使用 xpath 和 parse_url()):

    $xml = simplexml_load_string($your_html_here);
    $images = $xml->xpath("//img/@src");
    foreach ($images as $image) {
        $parsed = parse_url($image);
        print_r($parsed);
    }
    

    【讨论】:

      【解决方案3】:

      你也可以使用这个正则表达式:

       $string='<img src="path/to/image/file.jpg">';
       preg_match('/(?:\<img[\s].*?src=)(?:\"|\')(.*)?(?:\'|\")/',$string,$matches);
      

      $matches[1] 将为您提供 img 标记的确切 src 属性,无论您有多少属性在 img 标签中。

      从逻辑上讲,您可以使用的其他选项是在 '=' 上展开 (PHP),然后尝试查找 src 属性,这可能是一个更好的选择。

      【讨论】:

        【解决方案4】:

        其他正则表达式解决方案要么不必要地匹配整行,要么使用次优的模式语法。这是您将要找到的最小/最有效的正则表达式模式:

        <img.*?src=['"]\K[^\'"?]+
        

        (Pattern Demo Link)

        它也没有使用捕获组,因此preg_match_all() 的输出数组将小 50%。

        代码(Demo):

        $wp_post_content='<img src="http://example.com/wp-content/uploads/2013/11/dsc_0546.jpg?w=640">
        <img src="http://example.com/wp-content/uploads/2013/12/dsc_0547.jpg?w=1080">';
        
        var_export(preg_match_all('/<img.*?src=[\'"]\K[^\'"?]+/i',$wp_post_content,$out)?$out[0]:[]);
        

        输出:

        array (
          0 => 'http://example.com/wp-content/uploads/2013/11/dsc_0546.jpg',
          1 => 'http://example.com/wp-content/uploads/2013/12/dsc_0547.jpg',
        )
        

        【讨论】:

          猜你喜欢
          • 2013-02-03
          • 1970-01-01
          • 2011-08-30
          • 2016-07-21
          • 1970-01-01
          • 1970-01-01
          • 2011-03-04
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多