提取准确的URL';php中的字符串

提取准确的URL';php中的字符串,php,Php,我需要使用php从字符串中提取所有url,我参考了下面的url,但没有得到我想要的确切结果。 我的绳子在下面 $string = "hi new image one http://xxx/images/c4ca4238a0b923820dcc509a6f75849b208754572.jpgand two arehttp://yyy/images/c1f1a611c1147c4054c399c01f8bad76686484492.jpgend"; $regex = '#\bhttps?://[^

我需要使用php从字符串中提取所有url,我参考了下面的url,但没有得到我想要的确切结果。 我的绳子在下面

$string = "hi new image one http://xxx/images/c4ca4238a0b923820dcc509a6f75849b208754572.jpgand two arehttp://yyy/images/c1f1a611c1147c4054c399c01f8bad76686484492.jpgend";
$regex = '#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#';
preg_match_all($regex, $string, $matches);
echo "<pre>";
print_r($matches[0]); 
它只显示一个结果,但在字符串2url中可用,是否可以得到下面的结果

<?php
$string = "hi new image one http://xxx/images/c4ca4238a0b923820dcc509a6f75849b208754572.jpgand two are http://yyy/images/c1f1a611c1147c4054c399c01f8bad76686484492.jpgend";
$regex = '#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#';

preg_match_all($regex, $string, $matches);
echo "<pre>";

for($i=0;$i<sizeof($matches);$i++){
    print_r($matches[$i]); 
}
如何删除url前面和结尾的附加文本,并从字符串中筛选准确的url?感谢您的任何帮助

您可以创建一个for循环。 与数组的大小$matches匹配 然后打印结果

$regex = '#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#';
//         ^^ note this

问题在于您正在将链接与http单词的

Array (
    [0] => http://xxx/images/c4ca4238a0b923820dcc509a6f75849b208754572.jpgend
    [1] => http://yyy/images/c1f1a611c1147c4054c399c01f8bad76686484492.jpgand
)
应该与url末尾的某个固定后缀匹配

我假设您希望匹配jpg、jpeg、png图像,因此您的模式可能如下所示:

$regex='#https?:/[^,\s()]+(?:\([\w\d]+\)|([^,[:punct:][\s]|/)\(jpg | jpeg | png))#;

活生生的例子:

这是你问题的答案


这些是真实的url吗?不,只是我将主机地址替换为xxx和YYYY,但url的结尾,它们是您的输入url吗?使用
@http://[^\s]+.jpg
@mohammad使用“@http://[^\s]+(jpg | png | gif | swf | jpeg”)解决了一个非常简单的问题,+1作为答案,它也给出了确切的结果,但哈桑给出了简单的解决方案
$regex = '#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#';
//         ^^ note this
$regex = '#https?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#';
Array (
    [0] => http://xxx/images/c4ca4238a0b923820dcc509a6f75849b208754572.jpgend
    [1] => http://yyy/images/c1f1a611c1147c4054c399c01f8bad76686484492.jpgand
)
$regex = '#https?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/)\.(jpg|jpeg|png))#';
    $string = "hi new image one http://xxx/images/c4ca4238a0b923820dcc509a6f75849b208754572.jpg  and two are http://yyy/images/c1f1a611c1147c4054c399c01f8bad76686484492.jpg end";
    $strArray = explode(' ', $string);
    $newString = "";
    $url = array();
    foreach($strArray as $word)
    {
      if (substr($word, 0, 7) == "http://" || substr($word, 0, 8) == "https://")
      {
        $url[] = $word;
      } else {
        if ($newString != '')
          $newString .= ' ';
        $newString .= $word;
      }
    }

     print_r($url);