-1

如何用单行 preg_replace() 来实现以下输出?

$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 "";

我尝试了以下方法,例如 $string1 但不适用于上面的 $string2:

$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);

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

4

1 回答 1

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;
于 2010-11-20T11:24:10.260 回答