用逗号替换字符串或不用preg_replace替换字符串

时间:2012-02-19 00:01:49

标签: php regex 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 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分: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>