从PHP字符串中获取URL

时间:2011-10-04 13:31:49

标签: php regex

  

可能重复:
  PHP if string contains URL isolate it

我想使用某种正则表达式来提取任何类型的链接,例如www.google.com或http://google.comhttps://google.com,或者只是从字符串中提取google.com

我使用过这样的东西..但它只检测带有http和https的链接

$regex ="/(https?:\/\/[^\s]+)/";
$string ="is there a link http://google.com in this string?";
preg_match($regex, $string,$matches);
print_r($matches);

我得到的输出是

Array ( [0] => http://google.com)

我想检测字符串中所有类型的可能链接。

任何帮助将不胜感激! :)

2 个答案:

答案 0 :(得分:1)

我用超链接替换所有网址,但你可以随心所欲。

function formatUrlsInText($text)
{

    $reg_exUrl = "%^((http|https|ftp|ftps?://)|(www\.))([a-z0-9-].?)+(:[0-9]+)?(/.*)?$%i";
    preg_match_all($reg_exUrl, $text, $matches);
    $usedPatterns = array();
    foreach($matches[0] as $pattern){
        if(!array_key_exists($pattern, $usedPatterns)){
            $usedPatterns[$pattern]=true;
            $text = str_replace  ($pattern, "<a href='{$pattern}' rel='nofollow' target='_blank'>{$pattern}</a> ", $text);
        }
    }
    return $text;
}

答案 1 :(得分:0)

只需使用替换来覆盖其他模式。尝试这样的事情:

(https?:\/\/[^\s]+|\bwww\.[^\s]+|[^\s]+\.(?:com|org|uk)\b)

在此处查看online on Regexr

第一部分是你的。第二部分将匹配以www.开头的所有内容,第三部分将匹配以此列表中的内容结尾的所有内容(com | org | uk)。您可以将要匹配的任何域添加到此列表中。

我很确定这会匹配许多不是有效网址的内容,但如果您对正则表达式感到满意,可能其他两种模式也可以满足您的需求。