2010-11-20 91 views
-1

如何用一行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); 

我认为非捕获组(?:...)可能的工作,但我无法弄清楚...

+0

我对这个“摆脱”感到困惑。它总是“摆脱”吗?或者它可以是别的吗?目前尚不清楚。 – BeemerGuy 2010-11-20 11:23:10

+0

,你说它没有“[链接]”时失败,那么就不会有任何输出......失败是什么? – BeemerGuy 2010-11-20 11:24:31

+0

'摆脱'可能是任何非括号内的文本,说“等等等等等等等等等等等等等等等等等等等等等等等等等。现在更清楚了吗? - 我修改了原始问题,参见上面:... – ajo 2010-11-20 11:43:33

回答

0

为什么不只是如果?

if ($output = preg_replace($regex,'<a href=jp.php?jp=\1>[\1]</a>',$string1)) 
echo $output; 

编辑:您正则表达式将无法正常工作,preg_replace函数将替换所有匹配的文本,所以你将需要之前和链接参数后,也使文本...线沿线的:

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; 
+0

它确实有效! “旭日(cf [干])+ [乙]奇”正确链接“[干] [乙]” – ajo 2010-11-20 11:54:59

+0

是的,但你想只替换链接,这样它也删除你不想要的文字影响... – 2010-11-20 11:56:42

+0

??作为我最后一条评论的输出正是我想要的,但是如果没有包含“[。]”的构造,我会与空输出纠缠.... – ajo 2010-11-20 11:59:52