PHP正则表达式函数preg_replace用法实例分析

Charlotte ·
更新时间:2024-09-20
· 946 次阅读

本文实例讲述了PHP正则表达式函数preg_replace用法。分享给大家供大家参考,具体如下:

preg_replace 执行一个正则表达式的搜索和替换

语法:preg_replace (pattern ,replacement ,subject,limit,count )

参数 描述
pattern 正则表达式(字符串或字符串数组)
replacement 用于替换的字符串或字符串数组
subject 要进行搜索和替换的字符串或字符串数组。
limit 可选。每个模式在每个subject上进行替换的最大次数。默认是 -1(无限)。
count 可选。完成的替换次数

Example 1

$string = 'huang yu xin'; $pattern = '/(\w+) (\w+) (\w+)/i'; $replacement = '${1}a $3'; // $1对应(\w+),${1}a是区别$1a,说明是$1和a不是$1a,$3对应第三个(\w+) echo preg_replace($pattern, $replacement, $string);

结果是:

huanga xin

Example 2

$string = "nice to meet you"; $pattern = array(); $replace = array(); echo preg_replace(array('/nice/', '/you/'), array('Nice', 'me'), $string);

结果:

Nice to meet me

Example 3

$str = 'nice !'; $str = preg_replace('/\s+/', '', $str); echo $str;

结果:

nice!

Example 4

$count = 0; echo preg_replace(array('/\d/', '/[a-z]/'), '*', 'xp 4 to', -1, $count); echo $count;

结果:

** * **5

PS:这里再为大家提供2款非常方便的正则表达式工具供大家参考使用:

JavaScript正则表达式在线测试工具:
http://tools.jb51.net/regex/javascript

正则表达式在线生成工具:
http://tools.jb51.net/regex/create_reg

更多关于PHP相关内容感兴趣的读者可查看本站专题:《php正则表达式用法总结》、《php程序设计安全教程》、《php安全过滤技巧总结》、《PHP数组(Array)操作技巧大全》、《PHP基本语法入门教程》、《php字符串(string)用法总结》及《php+mysql数据库操作入门教程》

希望本文所述对大家PHP程序设计有所帮助。

您可能感兴趣的文章:PHP 字符串正则替换函数preg_replace使用说明PHP正则替换函数preg_replace和preg_replace_callback使用总结php正则之函数 preg_replace()参数说明PHP 正则表达式之正则处理函数小结(preg_match,preg_match_all,preg_replace,preg_split)php正则preg_replace_callback函数用法实例PHP正则替换函数preg_replace()报错:Notice Use of undefined constant的解决方法分析PHP 正则表达式常用函数使用小结PHP正则表达式基本函数 修饰符 元字符和需转义字符说明PHP 正则表达式函数库(两套)PHP 正则表达式常用函数PHP中的正则表达式函数介绍php 正则匹配函数体



php正则 preg_replace replace PHP

需要 登录 后方可回复, 如果你还没有账号请 注册新账号