查找并替换操作

时间:2012-04-12 01:22:44

标签: php preg-replace replace

我正在尝试使用PHP来查找和替换给定的字符串。我想这与您在文本编辑器(正则表达式或类似文件)中可能执行的操作类似。

这是一个示例初始字符串:

[quote=Registered_User;0123456]This is a message.[/quote]

所需的输出:

[quote=Registered_User pid=0123456]This is a message.[/quote]

我已经尝试过使用preg_replace(),但是当我想保留数字元素时会出现问题。

我无法使用str_replace()替换';'使用'pid ='因为初始字符串中可能存在发现孤立的分号的实例。

感谢您的时间。

3 个答案:

答案 0 :(得分:3)

我们可以在quote=之后找到一个单词,分号和数字后面的实例,然后用新格式替换它:

preg_replace("/quote=(\w+);(\d+)/", "quote=$1 pid=$2", $string);

答案 1 :(得分:0)

如果字符串“Registered_User; 0123456”的开头这是一条消息“不会改变,你可以像下面那样。

$string = "[quote=Registered_User;0123456]This is a message.[/quote]";
$beginStr = "[quote=Registered_User pid=";
$string = $beginStr . substr($string,23);

答案 2 :(得分:-1)

这将找到一个以15个单词字符开头的分号,前面带有“quote =”,并将该分号更改为“pid =”,但这只有在单词(Registered_User)为15个字符时才有效。

preg_replace("/(?<=([quote=]{6}(\w{15})));/", " pid=", $string);