Heim  >  Artikel  >  Backend-Entwicklung  >  php str_replace与preg_replace用法区别_PHP教程

php str_replace与preg_replace用法区别_PHP教程

WBOY
WBOYOriginal
2016-07-20 11:02:391002Durchsuche

 

str_replace() 函数使用一个字符串替换字符串中的另一些字符。

简单替换

echo str_replace("world","john","hello world!");
?>

利用正则表达式来替换

语法:stringobj.replace(rgexp, replacetext)
用str.replace("|",",") 只会替换第一个匹配的字符, str.replace(/|/g,",")则可以替换掉全部匹配的字符(g为全局标志)。


语法
preg_replace(find,replace,string,count)

preg_replace -- 执行正则表达式的搜索和替换
说明
mixed preg_replace ( mixed pattern, mixed replacement, mixed subject [, int limit])


在 subject 中搜索 pattern 模式的匹配项并替换为 replacement。如果指定了 limit,则仅替换 limit 个匹配,如果省略 limit 或者其值为 -1,则所有的匹配项都会被替换。

实例

$string = "april 15, 2003";
$pattern = "/(/w+) (/d+), (/d+)/i";
$replacement = "/${1}1,/$3";
print preg_replace($pattern, $replacement, $string);

/* output
   ======

april1,2003

*/
?>

替换数个值

$patterns = array ("/(19|20)(/d{2})-(/d{1,2})-(/d{1,2})/",
                   "/^/s*{(/w+)}/s*=/");
$replace = array ("//3///4///1//2", "$//1 =");
print preg_replace ($patterns, $replace, "{startdate} = 1999-5-27");
?>

本例将输出:

$startdate = 5/27/1999
 


例子 4. 使用 /e 修正符

preg_replace ("/(]*>)/e",
              "'//1'.strtoupper('//2').'//3'",
              $html_body);
?>

这将使输入字符串中的所有 html 标记变成大写
 

区别preg_replace函数主要用于正则比较方便而str_replace替换字符效率更好,但他们都用于字符替换的函数。


www.bkjia.comtruehttp://www.bkjia.com/PHPjc/445351.htmlTechArticlestr_replace() 函数使用一个字符串替换字符串中的另一些字符。 简单替换 echo str_replace(world,john,hello world!); ? 利用正则表达式来替换 语法:s...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn