Reputation: 2752
What i'm gonna do is:
$oneline="[a]http://first.com/hi_underscoredot.htm[/a] [a]http://secondinoneline.com/hi_.htm[/a]";
$changeToHTML=preg_replace("/\[a\](.*)\[\/a\]/","<a href='$1'>$1</a>",$oneline);
The output expected is
echo $changeToHTML;
OUTPUT >> http://first.com/hi_underscoredot.htm http://secondinoneline.com/hi_.htm
But the real output is (which is not as expected):
echo $changeToHTML;
OUTPUT >> http://first.com/hi_underscoredot.htm[/a][a]http://secondinoneline.com/hi_.htm
As you can see the very last output just above this text, you can see [/a][a] not replaced and the link is become as ONE LINK. I don't want that.
I want they seperated as TWO LINKS?
How?
Anybody can help me?
p/s: this is in one line.
Upvotes: 1
Views: 462
Reputation: 10744
A much more simple fix than those already given:
$changeToHTML=preg_replace("/\[a\](.*?)\[\/a\]/","<a href='$1'>$1</a>",$oneline);
Works fine.
The combination *?
means: Between zero and unlimited times, as few times as possible, expanding as needed [lazy]. Also see this helpful site to check your regex online.
Upvotes: 2
Reputation: 4308
(.*) is currently matching as much as it can, which is its default behavior. You want it to match only until the delimiters are found, and nothing more. To that end, you can invert the greediness of the PCRE engine using the U modifier like so :
$changeToHTML=preg_replace("/\[a\](.*)\[\/a\]/U","<a href='$1'>$1</a>",$oneline);
see this page for more details : http://php.net/manual/en/reference.pcre.pattern.modifiers.php
Upvotes: 1
Reputation: 17647
Use this instead:
(\[a\])([^\[]+)(\[\/a\])
with a replace pattern of
<a href='$2'>$2</a>
$re = '/(\[a\])([^\[]+)(\[\/a\])/';
$str = "[a]http://first.com/hi_underscoredot.htm[/a] [a]http://secondinoneline.com/hi_.htm[/a]";
$subst = "<a href='$2'>$2</a>";
$result = preg_replace($re, $subst, $str);
/* Prints:
<a href='http://first.com/hi_underscoredot.htm'>http://first.com/hi_underscoredot.htm</a> <a href='http://secondinoneline.com/hi_.htm'>http://secondinoneline.com/hi_.htm</a>
*/
Upvotes: 1
Reputation: 4066
your problem is .*
, instead of it write something like [^\[]*
$changeToHTML=preg_replace("/\[a\]([^\[]*)\[\/a\]/","<a href='$1'>$1</a>",$oneline);
Upvotes: 2