Convert a text link to a href link

Asked

Viewed 798 times

2

I have a site where I have an editor (html) only q sometimes instead of using the button to post the link people paste the link and it is in text so I am a regular expression to convert the text to link

$reply = preg_replace(
    "/(?<![\>https?:\/\/|href=\"'])(?<http>(https?:[\/][\/]|www\.)([a-z]|[A-Z]|[0-9]|[\/.&?= ]|[~])*)/",
    "<a href=\"$1\">$1</a>",
    $reply
);

It happens that if the link has "-"

http://www.webmotors.com.br/comprar/audi/a6/3-0-limousine-v6-30v-gasolina-4p-multitronic/4-portas/2002/13395497

this link does not work, it cuts in "-"

2 answers

0


For this just add the hyphenate and the underscore on the catch list.

(?<![\>https?:\/\/|href=\"'])(?<http>(https?:[\/][\/]|www\.)([a-z]|[A-Z]|[0-9]|[\/.&?=\-_ ]|[~])*)
                                                                                       ^^

Your code will look like this:

$reply = preg_replace(
"/(?<![\>https?:\/\/|href=\"'])(?<http>(https?:[\/][\/]|www\.)([a-z]|[A-Z]|[0-9]|[\/.&?=\-_ ]|[~])*)/",
"<a href=\"$1\">$1</a>",
$reply);

DEMO

  • But the solution does not work with this link http://cs624822.vk.me/v624822852/24ca1/KJepZpJimf0.jpg ou esse http://imworld.aufeminin.com/story/20150108/caique-laura-e-marocs-570188_w1000.jpg

  • @Daniellemes In the first link works yes, in the second did not work because it contained an underline _, I already updated the answer and put that too.

0

One suggestion is to simplify and join the - in regex.

/(?<![\>https?:\/\/|href=\"'])(?<http>(https?:[\/][\/]|www\.)([a-zA-Z0-9\/.&?=-~-]+)*)/

Example: https://regex101.com/r/pN8lY1/1

the part I changed was for [a-zA-Z0-9\/.&?=-~-]+, removed the | and put it together - in the character possibilities. I removed the blank space, which a URL should not have.

  • This code does not insert http:// if I type in the text www.abc.com.br will convert to link as <a href="www.abc.com.br">www.p3h8.com.br</a> absent http:// the link does not work.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.