1

Here is the code i am using

function parseURL($text) {
    $regex = "#\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))#iS";
    preg_match_all($regex, $text, $matches);
    foreach($matches[0] as $pattern){
        $text = str_replace($pattern, "<a href=\"$pattern\" target=\"_blank\">$pattern</a> ", $text);   
    }
    return $text;
}

For some reason my regex is outputting the following results: (bold = linked)

www.domain.com

http://www.domain.com

http://domain.com

so it works fine except if it contains both http and www at which point it only links from the www part onward.

any idea why?

EDIT

For anyone reading this requiring the fix, here is the working code thanks to Wiktor Stribiżew..

function parseURL($text) {
    $regex = "@\b(([\w-]+://?|www[.])[^\s()<>]+(?:\(\w+\)|([^[:punct:]\s]|/)))@i";
    $subst = "<a href='$0' target='_blank'>$0</a>";
    $text = preg_replace($regex, $subst, $text);
    return $text;
}
4
  • Why are you replacing matches? Just use preg_replace directly. Also, S makes no sense here (even if you meant to use s, DOTALL). See this PHP demo. Commented Feb 2, 2017 at 11:35
  • 1
    Is there any reason, why you don't use php.net/manual/en/function.parse-url.php? Commented Feb 2, 2017 at 11:35
  • @Anant its when there is more than one url in the $text string Commented Feb 2, 2017 at 11:40
  • @Wiktor Stribiżew - Ah yeah, i've been trying for that long i forgot i was using str_replace which was my problem! Thanks, my issue is now solved. Commented Feb 2, 2017 at 11:48

1 Answer 1

1

You do not need to first collect matches and then replace each one by one. Use a preg_replace directly and use a $0 backreference to refer to the whole match from the replacement pattern.

See the PHP demo:

$re = '@\b(([\w-]+://?|www[.])[^\s()<>]+(?:\(\w+\)|([^[:punct:]\s]|/)))@i';
$str = "www.domain.com\nhttp://www.domain.com\nhttp://domain.com";
$subst = '<a href="$0" target="_blank">$0</a> ';
$result = preg_replace($re, $subst, $str);
echo $result;

Output:

<a href="www.domain.com" target="_blank">www.domain.com</a> 
<a href="http://www.domain.com" target="_blank">http://www.domain.com</a> 
<a href="http://domain.com" target="_blank">http://domain.com</a> 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.