在php中使用正则表达式子模式而不是使用正则表达式2次
我感兴趣的是,是否可以将include子模式(子模式)转换为另一个模式,使我能够将这两个preg_匹配和preg_匹配全部转换为一个preg_匹配/preg_匹配全部在php中使用正则表达式子模式而不是使用正则表达式2次,php,regex,preg-match,preg-match-all,Php,Regex,Preg Match,Preg Match All,我感兴趣的是,是否可以将include子模式(子模式)转换为另一个模式,使我能够将这两个preg_匹配和preg_匹配全部转换为一个preg_匹配/preg_匹配全部 <?php $data = 'office phones tel1 6665555998 tel2 555666888 tel3 555688855 home phones tel1 555222555 tel2 555222444 tel3 555666888'; preg_match('/phones(.*)home
<?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)
您可以将\G
锚定与全球研究(preg\u match\u all)结合使用:
\G
是最后一次匹配后字符串中位置的锚定,当尚未匹配(在开始时)时,它相当于\A
锚定
\K
用于从匹配结果中删除匹配的左侧部分。
$data = 'office phones tel1 6665555998 tel2 555666888 tel3 555688855 home phones tel1 555222555 tel2 555222444 tel3 555666888';
preg_match_all('/[0-9]{4,12}/', $data, $matches); // 2nd operation
var_dump($matches);
像这样使用正向前瞻(?=.*home)
您可以将第一个preg\u match\u all
开始(office)和结束(home)值更改为您想要的任何值,然后匹配该组的电话号码。似乎就是我要找的!必须仔细分析并更好地理解它:)结果似乎就是我想要的!非常感谢。但我只想要办公室电话。你的密码也可以得到家庭电话。这也是一个很好的方法。但它似乎结束了搜索和“home”字符串。如果在办公室之前还有其他电话呢?例如:其他电话:tel1 555222555 tel2 555222444 tel3 555666888办公电话[…]?您需要将字符串home
更改为适合您的任何字符串。是的。这很有效。但正如前面提到的。只有1个preg_匹配或preg_匹配全部。这个问题与其说是为了解决某个问题,不如说是出于好奇。
$data = 'office phones tel1 6665555998 tel2 555666888 tel3 555688855 home phones tel1 555222555 tel2 555222444 tel3 555666888';
preg_match_all('/[0-9]{4,12}/', $data, $matches); // 2nd operation
var_dump($matches);
<?php
$data = 'office phones tel1 6665555998 tel2 555666888 tel3 555688855 home phones tel1 555222555 tel2 555222444 tel3 555666888';
preg_match_all('/([\d]{2,})(?=.*?home)/', $data, $matches, PREG_PATTERN_ORDER);
print_r($matches[1]);
Array
(
[0] => 6665555998
[1] => 555666888
[2] => 555688855
)
?>
$pnlist = "office phones tel1 6665555998 tel2 555666888 tel3 555688855 home phones tel1 555222555 tel2 555222444 tel3 555666888";
/*1*/ preg_match_all('/(?:office)(.*?)(?:home)/', $pnlist, $result, PREG_PATTERN_ORDER);
/*2*/ preg_match_all('/([\d]{2,})/', $result[1][0], $pn, PREG_PATTERN_ORDER);
print_r($pn[1]);
/*
Array (
[0] => 6665555998
[1] => 555666888
[2] => 555688855
)
*/