PHP preg_replace/preg_match vs PHP str_replace
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5245513/
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
PHP preg_replace/preg_match vs PHP str_replace
提问by benhowdle89
Can anyone give me a quick summary of the differences please?
任何人都可以给我一个差异的快速总结吗?
To my mind they both do the same thing?
在我看来,他们都做同样的事情?
Thanks
谢谢
回答by mingos
str_replace
replaces a specific occurrence of a string, for instance "foo" will only match and replace that: "foo". preg_replace
will do regular expression matching, for instance "/f.{2}/" will match and replace "foo", but also "fey", "fir", "fox", "f12", etc.
str_replace
替换字符串的特定出现,例如“foo”只会匹配并替换它:“foo”。preg_replace
将进行正则表达式匹配,例如“/f.{2}/”将匹配并替换“foo”,但也会匹配和替换“fey”、“fir”、“fox”、“f12”等。
[EDIT]
[编辑]
See for yourself:
你自己看:
$string = "foo fighters";
$str_replace = str_replace('foo','bar',$string);
$preg_replace = preg_replace('/f.{2}/','bar',$string);
echo 'str_replace: ' . $str_replace . ', preg_replace: ' . $preg_replace;
The output is:
输出是:
str_replace: bar fighters, preg_replace: bar barhters
str_replace:酒吧战士,preg_replace:酒吧barhters
:)
:)
回答by Jon
str_replace
will just replace a fixed string with another fixed string, and it will be much faster.
str_replace
只会用另一个固定字符串替换一个固定字符串,它会快得多。
The regular expression functions allow you to search for and replace with a non-fixedpattern called a regular expression. There are many "flavors" of regular expression which are mostly similar but have certain details differ; the one we are talking about here is Perl Compatible Regular Expressions (PCRE).
正则表达式函数允许您搜索和替换称为正则表达式的非固定模式。正则表达式有很多“风味”,它们大多相似,但在某些细节上有所不同;我们在这里谈论的是 Perl 兼容正则表达式 ( PCRE)。
If they look the same to you, then you should use str_replace
.
如果它们在您看来相同,那么您应该使用str_replace
.
回答by Mārti?? Briedis
str_replace
searches for pure text occurences while preg_replace
for patterns.
str_replace
搜索纯文本出现,同时preg_replace
搜索模式。