-1

I'm looking for a way to modify this function, which I found here, so that it doesn't change the tags I already have.

function make_links_clickable($text){
return preg_replace('!(((f|ht)tp(s)?://)[-a-zA-Zа-яА-Я()0-9@:%_+.~#?&;//=]+)!i', '<a href="$1">$1</a>', $text);}

For example, while it works great at turning regular text into links, it also turns this:

<a href="https://stackoverflow.com/">stackoverflow</a>

Into this:

https://stackoverflow.com/">stackoverflow

As I'm a beginner, and not very familiar with regexp, I'd appreciate it if there was a simple solution to this that doesn't require making the code a lot more complicated than it already is.

iai44
  • 1

2 Answers2

0
^(?<!href=["'])(?P<link>https?:\/\/(?:(?P<subdomain>(?:.*?\.)*?)(?P<domain>[^.]*))(?P<tld>\.[^.\n]+|\.co\.[^\/]+)(?P<path>(?:\/.*?|)))$

Using this regex and substitution, you should be able to do this.

Check it out on Regex101

In the substitution, I've done this:

<a href="${link}">${domain}</a>

Which turns these:

https://stackoverflow.com
http://www.bbc.co.uk/news

Into these:

<a href="https://stackoverflow.com">stackoverflow</a>
<a href="http://www.bbc.co.uk/news">bbc</a>

But does not touch this:

<a href="https://stackoverflow.com">stackoverflow</a>

If you want to do more with the other items, you can do, and I capture as much as I can so that you can mould this to your needs.

KyleFairns
  • 2,947
  • 1
  • 15
  • 35
0

I am pretty sure there exist a couple of duplicate questions but I cannot immediately find one (Note: I'm willing to close the question if someone provides a dupe link).

The answer is most probably to use a parser instead but for a quick & dirty solution you could as well use (*SKIP)(*FAIL) as in:

<a[^>]+>.+?</a>(*SKIP)(*FAIL)|\b(?:ftp|https?)://\S+

This needs to be replaced by

<a href="$0">$0</a>

The idea here is to match what you don't want, e.g. anything that looks like a link:

<a[^>]+>.+?</a>

And then to "throw the match away" and provide an alternative. See a demo on regex101.com.

Jan
  • 42,290
  • 8
  • 54
  • 79