【问题标题】:php regex get first URL from stringphp regex 从字符串中获取第一个 URL
【发布时间】:2015-03-27 09:55:21
【问题描述】:

我在 PHP 中使用以下正则表达式从字符串中获取 URL

regex = '/https?\:\/\/[^\" ]+/i';
$string = "lorem ipsum http://google.com lorem ipusm dolor http://yahoo.com/something";
preg_match_all($regex, $string, $matches);
$urls = ($matches[0]);

$urls 返回所有 URL。怎么能只返回第一个 URL?在这种情况下http://google.com

我试图在不使用 foreach 循环的情况下实现这一目标。

【问题讨论】:

标签: php regex


【解决方案1】:

根据documentation

preg_match_all — 执行全局正则表达式匹配

由于您只关注一个,您应该使用preg_match

执行正则表达式匹配

$regex = '/https?\:\/\/[^\" ]+/i';
$string = "lorem ipsum http://google.com lorem ipusm dolor http://yahoo.com/something";
preg_match($regex, $string, $matches);
echo $matches[0];

产量:

http://google.com

【讨论】:

    【解决方案2】:

    使用preg_match 代替 preg_match_all

    【讨论】:

      【解决方案3】:

      preg_match_all() 有一个标志参数,您可以使用它来对结果进行排序。您拥有变量 $matches 的参数是您的结果,应该列在该数组中。

      $matches[0][0];//is your first item.
      $matches[0][1];//is your second
      

      最好使用preg_match() 而不是preg_match_all()

      这是preg_match_all() 上用于您的标志的文档。 Link here!

      【讨论】:

        【解决方案4】:
        ^.*?(https?\:\/\/[^\" ]+)
        

        试试这个。抓住捕获或组。查看演示。

        https://regex101.com/r/pM9yO9/5

        $re = "/^.*?(https?\\:\\/\\/[^\\\" ]+)/";
        $str = "lorem ipsum http://google.com lorem ipusm dolor http://yahoo.com/something";
        
        preg_match_all($re, $str, $matches);
        

        【讨论】:

          【解决方案5】:

          只打印第 0 个索引。

          $regex = '/https?\:\/\/[^\" ]+/i';
          $string = "lorem ipsum http://google.com lorem ipusm dolor http://yahoo.com/something";
          preg_match_all($regex, $string, $matches);
          $urls = ($matches[0]);
          print_r($urls[0]);
          

          输出:

          http://google.com
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2014-06-24
            • 1970-01-01
            • 1970-01-01
            • 2015-02-08
            • 2018-07-11
            • 1970-01-01
            相关资源
            最近更新 更多