2011-07-21 38 views
1

返回URLS我有一个字符串的PHP数组它看起来像这样从PHP字符串

Array 
(
    [1] => Lorem ipsum dolor sit amet http://www.google.com/search?q=stackoverflow consectetur adipiscing elit. 
    [2] => Phasellus tempor vehicula fringilla. www.google.com/search?q=stackoverflow&ie=utf-8 
    [3] => google.com/search?q=stackoverflow&ie=utf-8 Aenean in cursus libero. 
); 

网址将是各种形式的,我需要的是这些链接的数组。像这样的:

Array 
(
    [1] => http://www.google.com/search?q=stackoverflow 
    [2] => http://www.google.com/search?q=stackoverflow&ie=utf-8 
    [3] => http://www.google.com/search?q=stackoverflow&ie=utf-8 
); 
+0

您是否认为互联网历史上没有人不得不从字符串解析URL,并且这样做的代码从未被共享过?好消息!已完成,代码已共享数千次!前往最近的搜索框。 –

+1

重复。 http://stackoverflow.com/questions/1113840/php-remove-url-from-string 这会有所帮助。 –

+0

既不以“google.com”开头,也不以“www.google.com”开头的字符串是有效的网址。提取所有可能的变化将是困难和模糊的。海事组织你应该首先确保这些网址是有效的。 – schneck

回答

2

代码为您提供:

$pattern = '/((https?|ftp)\:(\/\/)|(file\:\/{2,3}))?(((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))|(((([a-zA-Z0-9]+)(\.)?)+)(\.)(com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|[a-z]{2}))([\/][\/a-zA-Z0-9\.]*)*([\/]?(([\?][a-zA-Z0-9]+[\=][a-zA-Z0-9\%\(\)]*)([\&][a-zA-Z0-9]+[\=][a-zA-Z0-9\%\(\)]*)*))?/'; 

$a = array(
    'Lorem ipsum dolor sit amet http://www.google.com/search?q=stackoverflow consectetur adipiscing elit.', 
    'Phasellus tempor vehicula fringilla. www.google.com/search?q=stackoverflow&ie=utf-8', 
    'google.com/search?q=stackoverflow&ie=utf-8 Aenean in cursus libero.', 
); 

$urls = array(); 

foreach($a as $line) 
{ 
    if(!preg_match($pattern, $line, $match)) 
     continue; 

    $urls[] = $match[0]; 
} 

var_dump($urls); 

正则表达式是从here采取和纠正了一下。

+0

感谢您快速回答! – Povylas

+0

我测试了这个脚本,发现了一些弱点。它被特殊符号卡住,如 - 或_或?并且如果url结束时不能很好地处理.something(除了.html) – Povylas

0

你应该写一个适当的正则表达式来实现这一点。看看this