zoukankan      html  css  js  c++  java
  • PHP中 preg_replace()函数的使用

    定义

    preg_replace — 正则表达式匹配替换

    用法

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

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

    replacement may contain references of the form 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 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.

    下面举个例子,说明下

    示例

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

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

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

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


  • 相关阅读:
    random模块
    collections模块
    re模块
    正则表达式
    递归函数,二分查找
    内置函数,匿名函数
    python 中的爬虫· scrapy框架 重要的组件的介绍
    flask 中的常用组件的使用 ,virtualenv组件和 pipreqs组件 和 偏函数
    Django 中自带的 content_type表 , alipay的接口 需要的配置
    restful 和 restframework
  • 原文地址:https://www.cnblogs.com/jiaoran/p/12705294.html
Copyright © 2011-2022 走看看