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
5 Comments
NIKO_B
Exactly what i needed. Thanks you very much
Tom Udding
Note that this code will create fake links for invalid URLs between the
() part of []().Maciej Kozieja
It asumes nobody writes
')' in urlNIKO_B
That's definitely good to know. But in my case all the links are already validated.
Tom Udding
@NIKO_B then it won't be a problem :)