这篇文章主要介绍了PHP正则表达式函数preg_replace用法,结合实例形式分析了PHP正则表达式函数preg_replace基本功能、参数描述与相关使用技巧,需要的朋友可以参考下``````php本文实例讲述了PHP正则表达式函数preg_replace用法。分享给大家供大家参考,具体如下:preg_replace 执行一个正则表达式的搜索和替换语法:preg_replace (pattern ,replacement ,subject,limit,count )``````php参数 描述pattern 正则表达式(字符串或字符串数组)replacement 用于替换的字符串或字符串数组subject 要进行搜索和替换的字符串或字符串数组。limit 可选。每个模式在每个subject上进行替换的最大次数。默认是 -1(无限)。count 可选。完成的替换次数Example 1
2345$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 xinExample 2``````php1234$string = "nice to meet you";$pattern = array();$replace = array();echo preg_replace(array('/nice/', '/you/'), array('Nice', 'me'), $string);``````php结果:Nice to meet meExample 3
123$str = 'nice !';$str = preg_replace('/\s+/', '', $str);echo $str;
结果:nice!Example 4
123$count = 0;echo preg_replace(array('/\d/', '/[a-z]/'), '*', 'xp 4 to', -1, $count);echo $count;
结果:** * **5PS:这里再为大家提供2款非常方便的正则表达式工具供大家参考使用:JavaScript正则表达式在线测试工具:http://tools.jb51.net/regex/javascript正则表达式在线生成工具:http://tools.jb51.net/regex/create_reg
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号