Convert a text link to a href link

2

I have a website where I have an editor (html) only q sometimes instead of using the button to post the link people paste the link and it gets into text so I'm 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 "-"

link

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

    
asked by anonymous 06.03.2015 / 23:57

2 answers

0

To do this simply add the hyphen and the underscore in the capture list.

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

Your code will look similar to this:

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

DEMO

    
07.03.2015 / 00:07
0

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

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

Example: link

The part that I changed was [a-zA-Z0-9\/.&?=-~-]+ , I removed the | and added - to the character possibilities. I removed the space that a URL should not have.

    
07.03.2015 / 00:35