且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用php preg_replace替换HTML标签

更新时间:2021-11-09 21:59:32

您可以只使用str_replace:

You could just use str_replace:

$str = str_replace(array('<pre>', '</pre>'), array('<code>', '</code>'), $str);

如果您不得不使用正则表达式:

If you feel compelled to use regexp:

$str = preg_replace("~<(/)?pre>~", "<\\1code>", $str);

如果要单独替换它们:

$str = preg_replace("~<pre>~", '<code>', $str);
$str = preg_replace("~</pre>~", '</code>', $str);

您只需要转义该斜线即可.

You just need to escape that slash.