PHP preg_replace/preg_match与PHP str_replace [英] PHP preg_replace/preg_match vs PHP str_replace

查看:93
本文介绍了PHP preg_replace/preg_match与PHP str_replace的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以给我快速总结一下差异吗?

在我看来,他们俩都在做同一件事?

谢谢

解决方案

str_replace替换特定出现的字符串,例如,"foo"将仅匹配并替换该字符串:"foo". preg_replace将执行正则表达式匹配,例如"/f.{2}/"将匹配并替换"foo",但还将匹配并"fey","fir","fox","f12"等.

亲自看看:

$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;

输出为:

str_replace:酒吧战士,preg_replace:酒吧战士

:)

Can anyone give me a quick summary of the differences please?

To my mind they both do the same thing?

Thanks

解决方案

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.

[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

:)

这篇关于PHP preg_replace/preg_match与PHP str_replace的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆