PHP正则常用函数

下面这些php正则常用函数是我查阅资料结合网上的例子整理出来的。

1. preg_match()

  • 函数原型:int preg_match (string $pattern, string $content [, array $matches])
  • preg_match()函数在$content字符串中搜索与$pattern给出的正则表达式相匹配的内容。如果提供了$matches,则将匹配结果放入其 中。$matches[0]将包含与整个模式匹配的文本,$matches[1]将包含第一个捕获的与括号中的模式单元所匹配的内容,以此类推。该函数只作一次匹配,最终返回0或1的匹配结果数。
$content = "Current date and time is ".date("Y-m-d h:i a").", we are learning PHP together. 2017-05-08 01:33 pm.";
$pattern = "/([\d-]{10}) ([\d:]{5} [ap]m)/";
$res = preg_match($pattern, $content, $a);
print_r($res); //1
print_r($a);
// Array (
//      [0] => 2017-05-08 01:36 pm
//      [1] => 2017-05-08
//      [2] => 01:36 pm
// )

2. preg_match_all()

  • 函数原型:int preg_match_all (string $pattern, string $content [, array $matches])
  • 与preg_match()函数类似。如果使用了第三个参数,将把所有可能的匹配结果放入。本函数返回整个模 式匹配的次数(可能为0),如果出错返回False。
$content = "Current date and time is ".date("Y-m-d h:i a").", we are learning PHP together. 2017-05-08 01:33 pm.";
$pattern = "/([\d-]{10}) ([\d:]{5} [ap]m)/";
$res = preg_match_all($pattern, $content, $a);
print_r($res); //2
print_r($a);
// Array (
//      [0] => Array (
//                  [0] => 2017-05-08 01:39 pm
//                  [1] => 2017-05-08 01:33 pm
//             )
//      [1] => Array (
//                  [0] => 2017-05-08
//                  [1] => 2017-05-08
//              )
//      [2] => Array (
//                  [0] => 01:39 pm
//                  [1] => 01:33 pm
//              )
// )

3. preg_replace()

  • 函数原型:mixed preg_replace ( mixed pattern, mixed replacement, mixed subject [, int limit] )
  • 在 subject 中搜索 pattern 模式的匹配项并替换为 replacement。如果指定了 limit,则仅替换 limit 个匹配,如果省略 limit 或者其值为 -1,则所有的匹配项都会被替换。
  • replacement 可以包含 \n 形式或(自 PHP 4.0.4 起)$n 形式的逆向引用,首选使用后者。每个此种引用将被替换为与第 n 个被捕获的括号内的子模式所匹配的文本。n 可以从 0 到 99,其中 \0 或 $0 指的是被整个模式所匹配的文本。对左圆括号从左到右计数(从 1 开始)以取得子模式的数目。
$content = "Current date and time is ".date("Y-m-d h:i a").", we are learning PHP together. 2017-05-08 01:33 pm.";
$pattern = "/([\d-]{10}) ([\d:]{5} [ap]m)/";
$replacement = "$2, $1";
$res = preg_replace($pattern, $replacement, $content);
echo $res;
//Current date and time is 01:57 pm, 2017-05-08, we are learning PHP together. 01:33 pm, 2017-05-08.
  • preg_replace() 的每个参数(除了 limit)都可以是一个数组。如果 pattern 和 replacement 都是数组,将以其键名在数组中出现的顺序来进行处理。这不一定和索引的数字顺序相同。如果使用索引来标识哪个 pattern 将被哪个 replacement 来替换,应该在调用 preg_replace() 之前用 ksort() 对数组进行排序。
$content = "Current date and time is ".date("Y-m-d h:i a").", we are learning PHP together. 2017-05-08 01:33 pm.";
$pattern = array(
    0 => '/Current date and time/',
    1 => '/we are/',
    2 => '/PHP/',
);
$replacement = array(
    0 => 'Today',
    1 => 'they are',
    2 => 'JAVA',
);
$res = preg_replace($pattern, $replacement, $content);
echo $res;
//Today is 2017-05-08 02:08 pm, they are learning JAVA together. 2017-05-08 01:33 pm.

4. preg_replace_callback()

  • 函数原型:mixed preg_replace_callback ( mixed pattern, callback callback, mixed subject [, int limit] )
  • 本函数的行为几乎和 preg_replace() 一样,除了不是提供一个 replacement 参数,而是指定一个 callback 函数。该函数将以目标字符串中的匹配数组作为输入参数,并返回用于替换的字符串。

  • 回调函数 callback:一个回调函数,在每次需要替换时调用,调用时函数得到的参数是从subject 中匹配到的结果。回调函数返回真正参与替换的字符串。如果回调函数是个匿名函数,在PHP5.3中,通过关键字use,支持给匿名函数传多个参数。

1). 回调函数不是匿名函数

$content = "Hello 1, I'm 2.he is 3.";
$pattern = "/(\d+)/";
function aaa($m){
    $a = array(
        1 => 'world',
        2 => 'Ella',
        3 => 'Jack'
    );

    return $a[$m[0]];
}
$res = preg_replace_callback($pattern, 'aaa', $content);
echo $res;
//Hello world, I'm Ella.he is Jack.

2). 回调函数是匿名函数

$content = "Hello 1, I'm 2.he is 3.";
$pattern = "/(\d+)/";
$a = array(
    1 => 'world',
    2 => 'Ella',
    3 => 'Jack'
);
$res = preg_replace_callback($pattern, function($m) use($a){ //把$a作为参数传给匿名函数
    return $a[$m[1]];
}, $content);
echo $res;
//Hello world, I'm Ella.he is Jack.

3). 回调函数是在同一个类里的一个方法

class Obj {
    public function reg(){
        $content = "Hello 1, I'm 2.he is 3.";
        $pattern = "/(\d+)/";
        $res = preg_replace_callback($pattern, array($this, 'aaa'), $content);
        echo $res;
    }

    function aaa($m){
        $a = array(
            1 => 'world',
            2 => 'Ella',
            3 => 'Jack'
        );

        return $a[$m[0]];
    }
}

$obj = new Obj();
$obj->reg();
//Hello world, I'm Ella.he is Jack.

4). 回调函数是某个类里的一个方法

class Obj1 {
    function aaa($m){
        $a = array(
            1 => 'world',
            2 => 'Ella',
            3 => 'Jack'
        );

        return $a[$m[0]];
    }
}
$content = "Hello 1, I'm 2.he is 3.";
$pattern = "/(\d+)/";
$obj1 = new Obj1(); //实例化类Obj1
$res = preg_replace_callback($pattern, array($obj1, 'aaa'), $content); 
echo $res;
//Hello world, I'm Ella.he is Jack.

5. preg_filter()

  • 函数原型:mixed preg_filter ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
  • preg_filter()等价于preg_replace() 除了它仅仅返回(可能经过转化)与目标匹配的结果.
$content = array('1', 'a', '2', 'b', '3', 'A', 'B', '4');
$pattern = array(
    0 => '/\d/',
    1 => '/[a-z]/',
    2 => '/[a1]/',
);
$replacement = array(
    0 => 'A:$0',
    1 => 'B:$0',
    2 => 'C:$0',
);
$res1 = preg_filter($pattern, $replacement, $content);
print_r($res1);
// Array (
//      [0] => A:C:1
//      [1] => B:C:a
//      [2] => A:2
//      [3] => B:b
//      [4] => A:3
//      [7] => A:4
// )

$res2 = preg_replace($pattern, $replacement, $content);
print_r($res2);
// Array (
//      [0] => A:C:1
//      [1] => B:C:a
//      [2] => A:2
//      [3] => B:b
//      [4] => A:3
//      [5] => A
//      [6] => B
//      [7] => A:4
// )

6. preg_grep()

  • 函数原型:array preg_grep ( string $pattern, array $input [, int $flags] )
  • 返回给定数组input中与模式pattern 匹配的元素组成的数组.如果将flag设置为PREG_GREP_INVERT, 这个函数返回输入数组中与 给定模式pattern不匹配的元素组成的数组.
$content = array("pasta", "steak", "fish", "potatoes");
$pattern = '/p\w+/';
$res = preg_grep($pattern, $content);
print_r($res);
// Array (
//      [0] => pasta
//      [3] => potatoes
// )

7. preg_split()

  • 函数原型:array preg_split (string pattern, string string [, int limit [, int flags]]);
  • preg_split()函数操作和函数split()一模一样,除了正则表达式接受input参数作为匹配的元素。 如果指定,将限制分隔得到的子串最多只有limit个,返回的最后一个 子串将包含所有剩余部分。
$content = '123.456.789.000';
$pattern = '/\./';
$res = preg_split($pattern, $content);
print_r($res);
// Array (
//      [0] => 123
//      [1] => 456
//      [2] => 789
//      [3] => 000
// )

8. preg_quote()

  • 函数原型:string preg_quote ( string $str [, string $delimiter] )
  • preg_quote()需要参数 str 并向其中每个正则表达式语法中的字符前增加一个反斜线。如果你需要以动态生成的字符串作为模式去匹配则可以用此函数转义其中可能包含的特殊字符。如果提供了可选参数 delimiter,该字符也将被转义。可以用来转义 PCRE 函数所需要的定界符,最常用的定界符是斜线 /。
  • 正则表达式的特殊字符包括:. \ + * ? [ ^ ] $ ( ) { } = ! < > | :。
$content = '$40 for a g3/400';
$res = preg_quote($content, '/');
echo $res;
// \$40 for a g3\/400
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值