• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

PHP中preg_replace()函数的使用

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

定义

preg_replace — 正则表达式匹配替换

用法

preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )

搜索subject中符合pattern的部分,并用replacement替代。
replacement和pattern均可以是数组。
使用比较简单,功能和用法均类似于 str_replace.
比较难理解的是 replacement 可以后向引用。

replacement may contain references of the form \n or $n, with the latter form being the preferred one. Every such reference will be replaced by the text captured by the n'th parenthesized pattern. n can be from 0 to 99, and \0 or $0 refers to the text matched by the whole pattern. Opening parentheses are counted from left to right (starting from 1) to obtain the number of the capturing subpattern. Note that backslashes in string literals may require to be escaped.

示例

$string = 'April 15, 2003';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1}1,$3';
// \1=April \2=15 \3=2003  \均可用$代替
preg_replace($pattern, $replacement, $string);
//April1,2003

其中,双引号中 \ 和 $ 均需要转义,单引号不用,下面这几个是等价的

'${1}1,$3' == “\${1}1,\$3” == “\${1}1,\\3”

所以为了书写简洁,便于阅读,推荐全部使用单引号。



鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
php在虚拟机和windows上的应用发布时间:2022-07-10
下一篇:
Symfony没有安装依赖_PHPFatalerror:require():Failedopeningrequired发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap