如何用一行preg_replace()来实现以下输出?正则表达式的PHP:“摆脱[链接1]摆脱[链接2] ...摆脱” - 问题'摆脱'当有没有[链接]
$string1="get rid1 [link1] get rid2 [link2] ..."; // any number of 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 "";
我尝试以下,这适用于例如$字符串1而不是上面的字符串2 $:
$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);
我认为非捕获组(?:...)
可能的工作,但我无法弄清楚...
我对这个“摆脱”感到困惑。它总是“摆脱”吗?或者它可以是别的吗?目前尚不清楚。 – BeemerGuy 2010-11-20 11:23:10
,你说它没有“[链接]”时失败,那么就不会有任何输出......失败是什么? – BeemerGuy 2010-11-20 11:24:31
'摆脱'可能是任何非括号内的文本,说“等等等等等等等等等等等等等等等等等等等等等等等等等。现在更清楚了吗? - 我修改了原始问题,参见上面:... – ajo 2010-11-20 11:43:33