开发者

fetch a URL from a string PHP [duplicate]

开发者 https://www.devze.com 2023-04-11 04:27 出处:网络
This question already has answers here: Closed 11 years ago. 开发者_Python百科 Possible Duplicate: PHP if string contains URL isolate it
This question already has answers here: Closed 11 years ago. 开发者_Python百科

Possible Duplicate:

PHP if string contains URL isolate it

I would like to use some kind of regex to extract any type of links like www.google.com or http://google.com or https://google.com or just google.com from a string

I have used something like this..but it only detects links with http and https

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

The output I get is

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

I want to detect all types of possible links in a string.

Any help will be appreciated!! :)


I replace all URL with hyperlink but you can do whatever you want.

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;
}


Just make use of alternations to cover the other patterns. Try something like this:

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

See it here online on Regexr

The first part is yours. The second part will match everything that starts with www. and the third part will match everything that ends with something from this list (com|org|uk). You can add any domain you want to match to this list.

I am quite sure this will match a lot of stuff thats not a valid URL, but if you are happy with your Regex, probably the other two patterns are also fine for your need.

0

精彩评论

暂无评论...
验证码 换一张
取 消