使用正则表达式子模式来代替在php中使用正则表达式2次 [英] Using regular expression subpattern to instead of using regular expression 2 times in php

查看:28
本文介绍了使用正则表达式子模式来代替在php中使用正则表达式2次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很感兴趣是否可以将子模式(子模式)包含到另一个模式中,从而允许我将这2个PREG_MATCH和PREG_MATCH_ALL转换为一个PREG_MATCH/PREG_MATCH_ALL。

<?php

$data = 'office phones tel1 6665555998 tel2 555666888 tel3 555688855 home phones tel1 555222555 tel2 555222444 tel3 555666888';

preg_match('/phones(.*)home phones/', $data, $matches); // 1st operation
preg_match_all('/[0-9]{4,12}/',  $matches[1],  $matches); // 2nd operation

var_dump($matches);

// Question is: How to get same output with just only one preg_match

preg_match('/phones(SUBPATTERN)home phones/', $data, $result_data);

// Where SUBPATTERN is a pattern that would do exactly what 2nd operation did
// so $result_data contains what does $matches (array structure can be different can be 3 dimmensional array not only 2)

示例数据:https://eval.in/138817

注意:此问题是具有不同数据的另一种获取答案的方法:PHP Regular expression return submatches as array

推荐答案

您可以将G锚用于全局研究(PREG_MATCH_ALL):

$pattern = '~(?:office phones|G(?!A)) teld+ Kd{4,12}~';
preg_match_all($pattern, $data, $matches);

print_r($matches);

G是上次匹配后字符串中位置的锚点,当(开始时)还没有匹配时,它等同于A锚点。

K用于从匹配结果中删除匹配的左侧部分。

这篇关于使用正则表达式子模式来代替在php中使用正则表达式2次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆