Search code examples
regexpreg-replacepreg-match

Transform http:// link as text to a href but dont include <br> tag at the end


So i have this code:

preg_replace('/(http[s]?:\/\/[^\s]*[^,\s\.])/i', '<a href="$1">$1</a>', $post_text);

It allows me to create hyperlinks from links in text. That [^,\s\.]) in the end is when someone posts something like "Oh hey this is nice link http://google.com." - it gets rid of dot at the end (among other things) and doesn't include her in creating the ahref.

My problem is though when i have a line break just after that link. For example someone posts

"Oh hey this is nice link http://google.com

"

and my script is then feeded with

"Oh hey this is nice link http://google.com<br>"

Suddenly that <br> is included in link and i am very sad cuz that's not what i want :(

I tried this

preg_replace('/(http[s]?:\/\/[^\s]*[^,\s\.<br>])/i', '<a href="$1">$1</a>', $post_text);

but its not correct apparently.

Any help please?


Solution

  • (http[s]?:\/\/[^\s<>]*[^,\s\.<>])
    

    Hi,you just should add '< >'

    In you last regex,it matched <br> by the first [^\s]*