2012-02-19 61 views
0

我有這個值格式的字符串:用逗號或不替換字符串的preg_replace

$str = "Apple, Orange, Computer-Hardware, preg_replace, 50k"; 

$str = "Computer"; 

我怎麼能與preg_replace函數將其轉換爲:

$str = "<a href='p.php?s=Apple'>Apple</a>, <a href='p.php?s=Orange'>Orange</a>, 
<a href='p.php?s=Computer-Hardware'>Computer-Hardware</a>, <a href='p.php?s=preg_replace'>preg_replace</a>, <a href='p.php?s=50k'>50k</a>"; 

$str = "<a href='p.php?s=Computer'>Computer</a>"; 

回答

2
$str = preg_replace('/([\w-]+)/', '<a href=\'p.php?s=$1\'>$1</a>', $str); 
+0

在某些詞之間的字符串可以是這兩個字符 - ,_或數字:前:浸漬料-replcae,56K,50000 – Ali 2012-02-19 00:58:44

+0

@AliA:我已經更新了我的答案。 – 2012-02-19 01:09:00

+0

@TimCoorper:結果中逗號也用「Apple,」 – Ali 2012-02-19 02:45:35

0

試試看:

$str = "Apple, Orange, Computer-Hardware, preg_replace, 50k"; 
$str = preg_replace('/([^,\s]+)/', "<a href='p.php?s=$1'>$1</a>", $str); 
echo $str,"\n"; 

輸出:

<a href='p.php?s=Apple'>Apple</a>, <a href='p.php?s=Orange'>Orange</a>, <a href='p.php?s=Computer-Hardware'>Computer-Hardware</a>, <a href='p.php?s=preg_replace'>preg_replace</a>, <a href='p.php?s=50k'>50k</a> 
相關問題