如何使用单行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);
我认为非捕获组(?:...)
可能有效,但我无法弄明白......
答案 0 :(得分: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;