Using regular expression subpattern to instead of using regular expression 2 times in php(使用正则表达式子模式来代替在php中使用正则表达式2次)
本文介绍了使用正则表达式子模式来代替在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次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:使用正则表达式子模式来代替在php中使用正则表达式2次


猜你喜欢
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- PHP - if 语句中的倒序 2021-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01