0

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
  • 1
    Can you also provide an example of what you're trying to do? Commented Mar 19, 2017 at 13:58

1 Answer 1

2

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

Test if it works for you

Sign up to request clarification or add additional context in comments.

5 Comments

Exactly what i needed. Thanks you very much
Note that this code will create fake links for invalid URLs between the () part of []().
It asumes nobody writes ')' in url
That's definitely good to know. But in my case all the links are already validated.
@NIKO_B then it won't be a problem :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.