如何使用 php preg_replace 替换 HTML 标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3376051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use php preg_replace to replace HTML tags
提问by Juanjo Conti
I'd like to change <pre>with <code>and </pre>with </code>.
我想改变<pre>与<code>和</pre>用</code>。
I'm having problem with the slash / and regex.
我在使用斜杠 / 和正则表达式时遇到问题。
回答by NullUserException
You could just use str_replace:
你可以只使用 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);
If you want to replace them separately:
如果要单独替换它们:
$str = preg_replace("~<pre>~", '<code>', $str);
$str = preg_replace("~</pre>~", '</code>', $str);
You just need to escape that slash.
你只需要逃避那个斜线。
回答by JAL
You probably need to escape the /s with \s, or use a different delimiter for the expression.
您可能需要使用 \s 对 /s 进行转义,或者为表达式使用不同的分隔符。
Instead, though, how about using str_replace? <pre>and </pre>will be easy to match as they're not likely to contain any classnames or other attributes.
但是,如何使用str_replace呢?<pre>并且</pre>很容易匹配,因为它们不太可能包含任何类名或其他属性。
$text=str_replace('<pre>','<code>',$text);
$text=str_replace('</pre>','</code>',$text);
回答by starkeen
I found a very easy solution to replace multiple words in a string :
我找到了一个非常简单的解决方案来替换字符串中的多个单词:
<?php
$str="<pre>Hello world!</pre>";
$pattern=array();
$pattern[0]="/<pre>/";
$pattern[1]="/<\/pre>/";
$replacement=array();
$replacement[0]="<code>";
$replacement[1]="</code>";
echo preg_replace($pattern,$replacement,$str);?>
output :
输出 :
<code>Hello world!</code>
With this script you can replace as many words in a string as you want :
使用此脚本,您可以根据需要替换字符串中的任意多个单词:
just place the word (that you want to replace) in the pattern array , eg :
只需将单词(您要替换的)放在模式数组中,例如:
$pattern[0]="/replaceme/";
and place the characters (that will be used in place of the replaced characters) in the replacement array, eg :
并将字符(将用于代替被替换的字符)在替换数组中,例如:
$replacement[0]="new_word";
Happy coding!
快乐编码!

