-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 に答える