Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to replace tags in a string in PHP

Tags:

regex

url

php

I am using the PHP and Regex below to search through a huge string for

[LINK]www.anyurl.com[/LINK]

and replace it with:

<a href="http://www.anyurl.com">http://www.anyurl.com</a>

The http:// is prepended if http or ftp do not exist in front of the url already.

$re = '/\[LINK]((?:(?!(http|ftp)|\[\/LINK]).)*)\[\/LINK]/i'; 
$subst = '[LINK]http://$1[/LINK]'; 
$xtext = preg_replace($re, $subst, $xtext, 1);
$xtext = preg_replace("/(\[LINK\])(\S*)(\[\/LINK])/", "<a href=\"$2\" target='_blank'>$2</a>", $xtext);

My problem is it only appears to be working for the first match it comes to and not other [LINK]www.urls.com[/LINK] in the document. The document being $xtext

like image 812
MikeC Avatar asked Feb 03 '26 04:02

MikeC


1 Answers

Whoops, I have just found my error and it is so simple. In my third line:

$xtext = preg_replace($re, $subst, $xtext, 1);

I have 1 at the end of the preg_replace i.e. replace once. This should be set to -1 or left blank to replace all.

like image 199
MikeC Avatar answered Feb 04 '26 18:02

MikeC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!