regex php: "get rid [link1] get rid [link2] ... get rid" - problem 'getting rid' when there IS NO [link]
How to preg_replace() with a single line to achieve the following outputs?
$string1="get rid1 [link1] get rid2 [link2] ..."; // any number of开发者_StackOverflow社区 links
echo "[<a href=link1>link1</a>][<a href=link2>link2</a>]";
$string2="get rid any text any text get rid"; // = no links: is a possibility
echo "";
I tried the following, which works for example $string1 but not for $string2 above:
$regex="/".
"[^\[\]]*". // the non-bracketed text before: -> eliminate
"\[(.*?)\]". // the bracketed text: [.]: -> convert into links
"[^\[\]]*"; // get rid of non-bracketed text after: -> eliminate
"/";
echo preg_replace($regex,'<a href=jp.php?jp=\1>[\1]</a>',$string1);
I think non-capturing groups (?:...)
might work, but I can't figure it out...
Why not just if?
if ($output = preg_replace($regex,'<a href=jp.php?jp=\1>[\1]</a>',$string1))
echo $output;
Edit: your regex won't work, preg_replace will replace ALL of the matched text so you would need to make the text before and after the link arguments too... Along the lines of:
preg_replace("(text we dont want to replace)(text we do want to replace)(more junk text)",$1." altered $2 = ".$2." ".$3, $string1)
.
$output = preg_replace($regex,'<a href=jp.php?jp=\1>[\1]</a>',$string1);
if ($output != $string1)
echo $output;
精彩评论