PHP用链接替换字符串

时间:2012-06-10 06:33:39

标签: php regex

好的,感谢这个论坛上的人们,我终于得到了一个简单的推特在线网站。现在我遇到了另一个问题。

我有一个Twitter提示说示例文本是:

  

猫将始终放在包里@folks @charliesheen

现在我有了使用正则表达式查找文本中的所有@ _ 字符串并将其替换为

的想法
<a href="index.php?".$(matched_string - @)>matched_string</a>

关于如何做到这一点的任何想法?

1 个答案:

答案 0 :(得分:4)

这是我快速入侵的内容。 \S表示“任何不是空格的字符”。

$str = 'The cat will always be in the bag @folks @charliesheen';
$str = preg_replace('/@(\S*)/', '<a href="index.php?$1">$1</a>', $str);

编辑:为了安全起见,您应该确保网址中的所有字符都是“网址安全”。

$str = 'The cat will always be in the bag @folks @charliesheen';
$str = preg_replace_callback('/@(\S*)/', function($x){
    return '<a href="index.php?'.urlencode($x[1]).'">'.$x[1].'</a>';
}, $str);