I need some help converting all instances in a string that looks like this [text](url) into a clickable link like this <a href=“url“>text</a>?
1 Answer
You can use this regular exprestion \[(.*?)\]\s*\((.*?)\)
and replace with <a href="$2">$1</a>
like so
preg_replace('/\[(.*?)\]\s*\((.*?)\)/', '<a href="$2">$1</a>', '[text](url)');
\[(.*?)\]
select anything between [] and store it in first capture group
\((.*?)\)
select anything between () and store it in first capture group
$1
use content of first capture group
preg_replace ( $pattern , $replacement , $subject )
take a look
-
-
Note that this code will create fake links for invalid URLs between the
()
part of[]()
. Mar 19, 2017 at 14:11 -
-
That's definitely good to know. But in my case all the links are already validated.– NIKO_BMar 19, 2017 at 14:18
-