使用preg_replace()替换段落上的文本

时间:2013-06-23 14:36:51

标签: php

我刚刚在PHP中发现了函数preg_replace(),但我还不知道如何完全使用它。我在我的网站上有我需要更新的文本,我认为preg_replace()可以完成这项工作。

我需要替换类似的文字:

@kev need to replace the @ symbol at the end of this paragraph, @example...

要:

@kev need to replace the @ symbol at the end of this paragraph, example...

基本上:

@example...

要:

example...

我没有时间进一步研究这个功能,所以我真的需要问一下。谢谢!

2 个答案:

答案 0 :(得分:0)

这应该有效:

$str = '@kev need to replace the @ symbol at the end of this paragraph, @example...';
echo preg_replace('~@([\w]*?)\.\.\.~u', '$1...', $str);

输出:

@kev need to replace the @ symbol at the end of this paragraph, example...

答案 1 :(得分:0)

相当硬编码但有效的解决方案:

$string = "@kev need to replace the @ symbol at the end of this paragraph, @example..." ;

preg_match_all("/\s+@([a-zA-Z0-9]+)/", $string, $matches) ;
$new = preg_replace("/@{$matches[1][0]}/", "{$matches[1][0]}", $string);

echo $new ;