Skip to content
Advertisement

PHP Replace URLs in string with Anchor tag

I’m trying to parse a string that contains links in it. I’m happy to specify the format that they come across in, however normal HTML tags are being stripped out in transit.

I’m suggesting the following format:

[url=https://test.com]my link[/url]

becomes:

<a href="https://test.com" target="_blank">my link</a>

with no other attributes necessary.

I have the following preg replace but it’s not working

$result = preg_replace("/[burlb=[1-9a-zA-Z:.-/_]*?[]]*?[/burlb]/", "<a href='$1' target='_blank'>$2</a>", $str);

As soon as I try to get the link/text when building the regex I fall down.

Any help/simplification/other ideas greatly appreciated!

Advertisement

Answer

You may consider using

preg_replace('~[url=([^][s]+)](.*?)[/url]~s', "<a href='$1' target='_blank'>$2</a>", $text)

See the PHP demo and the regex demo.

Details

  • [url= – a [url= substring
  • ([^][s]+) – Group 1 ($1): any 1 or more characters other than [, ] and whitespace
  • ] – a ] char
  • (.*?) – Group 2 ($2): any zero or more characters, as few as possible
  • [/url] – a [/url] substring.
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement