如何从给定数据中获取任何URL

时间:2014-04-03 09:33:16

标签: php preg-match preg-match-all preg-split

我想从给定的数据中获取网址。

e.g。我有一个变量

中的数据
  

$data = "is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, http://www.youtube.com/watch?v=mm78xlsADgc when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but";

现在我想从给定变量$data获取此网址(http://www.youtube.com/watch?v=mm78xlsADgc)。请让我知道我该怎么做?

6 个答案:

答案 0 :(得分:0)

您应filter_var()执行此操作。

var_dump(filter_var('http://www.youtube.com/watch?v=', FILTER_VALIDATE_URL));

答案 1 :(得分:0)

使用this answer和您$data上方的模式:

preg_match_all(
    '#((?:http|https|ftp)://(?:\S*?\.\S*?))(?:\s|\;|\)|\]|\[|\{|\}|,|"|\'|:|\<|$|\.\s)#i',
    $data,
    $matches
);
var_dump($matches[1]);

See it in action on Ideone

根据您要匹配的网址类型,您可能想要使用实际使用的模式,但概念是相同的。

答案 2 :(得分:0)

试试这个

$data = "is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, http://www.youtube.com/watch?v=mm78xlsADgc when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but";
$array1 = explode(" ", $data);
$searchword = 'http';
$matches = array();
foreach($array1 as $k=>$v) {
    if(preg_match("/\b$searchword\b/i", $v)) {
       echo $matches[$k] = $v;
    }
}

答案 3 :(得分:0)

<?php  
$data = "is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, http://www.youtube.com/watch?v=mm78xlsADgc when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but";

preg_match('/(https?:.*?)\s+/si', $data, $url);

echo $url[0];
?>

DEMO

答案 4 :(得分:0)

怎么样:

preg_match_all(
    '#(https?://(?:\S+))#i',
    $data,
    $matches
);

\S代表任何不是空格的角色。

答案 5 :(得分:0)

使用此代码,它适用于我

$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

// The Text you want to filter for urls
$text = "is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, http://www.youtube.com/watch?v=mm78xlsADgc when an unknown printer took a galley of type and scrambled it to make a type   specimen book. It has survived not only five centuries, but";

// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {


       return preg_replace($reg_exUrl, $url[0], $text);

} 

}