MikeC
MikeC

Reputation: 146

Regex to replace tags in a string in 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

Upvotes: 3

Views: 141

Answers (3)

developerwjk
developerwjk

Reputation: 8659

In the first expression the 1 needed to be removed, as you already figured out. Notice the second expression is the same as your second expression but with * replaced with +?, and the unnecessary capture groups around the tags removed. * doesn't stop at the first [\LINK] but at the last one, resulting in a link with display text like http://www.google.com[/LINK]\n[LINK]http://www.yahoo.com so +? is needed.

$xtext = '[LINK]www.google.com[/LINK]\n[LINK]www.yahoo.com[/LINK]';

$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='$1' target='_blank'>$1</a>", $xtext);

Upvotes: 0

SomeoneYouDontKnow
SomeoneYouDontKnow

Reputation: 1299

I think your problem could be the greedyness of your first regex. As you prepend the http:// to your first found link, all other links will stay the same. So please try (note the additional questionmark in line one):

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

Upvotes: 0

MikeC
MikeC

Reputation: 146

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.

Upvotes: 1

Related Questions