2011-04-14 51 views
0

我需要从字符串中提取一些文本,然后用一个字符在一个实例中删除而不是另一个字符替换该文本。希望这个例子会告诉你我的意思是(这是我至今):在preg_replace函数期间删除字符

$commentEntry = "@Bob1990 I think you are wrong..."; 
$commentText = preg_replace("/(@[^\s]+)/", "<a target=\"_blank\" href=\"http://www.youtube.com/comment_search?username=${1}$1\">$1</a>", $commentEntry); 

我想要得到的结果是:

<a href="http://www.youtube.com/comment_search?username=Bob1990">@Bob1990</a> I think you are wrong... 

但我越来越:

<a href="http://www.youtube.com/[email protected]">@Bob1990</a> I think you are wrong... 

我一直在处理这个问题至少一个小时,几乎放弃了希望,所以任何帮助都非常感谢!

回答

3

可以尝试这样的事情

$commentText = preg_replace("/(@)([^\s]+)/", "<a target=\"_blank\" href=\"http://www.youtube.com/comment_search?username=$2\">$1$2</a>", $commentEntry); 
0

你可以做的是适应捕获。移动@了括号:

preg_replace("/@([^\s]+)/", 

然后,你可以写你的替换字符串像

'<a href="...$1">@$1</a>' 

注意如何第一$1刚刚重新插入文本,第二$1被逐字@前缀将其恢复。

0

您正在捕获@,因此在使用$1时它会始终输出。试试这个:

$commentText = 
    preg_replace(
    "/@([^\s]+)/", 
    "<a target=\"_blank\" href=\"http://www.youtube.com/comment_search?username=$1\">@$1</a>", 
    $commentEntry 
); 

这里的区别是,@不再捕获作为$1(部分即它会只捕获Bob1990因为它是一个文本值,它并不需要成为其中的一部分。任何模式,相反,我只是将其改为在元素文本中直接输出为文本值,即直接输入到捕获的名称之前(即它现在确实为<a>@$1</a>而不是<a>$1</a>

相关问题