Php preg_match_all-如何捕获所有子模式
A有以下内容:Php preg_match_all-如何捕获所有子模式,php,regex,regular-language,Php,Regex,Regular Language,A有以下内容: $pattern = "/\b(?:(one|two|three|four|five|(?:s|z)ix|seven|eight|nine|zero|twelve)(?:\s|-)*){4,8}/ix"; $subject = "one four-six nine twelve zero eight nine nine seven three six six"; $matches = []; preg_match_all ($pattern, $subject, $ma
$pattern = "/\b(?:(one|two|three|four|five|(?:s|z)ix|seven|eight|nine|zero|twelve)(?:\s|-)*){4,8}/ix";
$subject = "one four-six nine twelve
zero eight nine nine seven three six six";
$matches = [];
preg_match_all ($pattern, $subject, $matches, PREG_SET_ORDER);
我想看到的是,$matches
中所有分隔的单词,但我只得到了9个大模式的第一个单词和6个第二个-最后一个单词。我知道我可以把所有的单字放在括号里,但是有没有更好的方法呢?+这样我就可以得到空字符串了
输出如下:
array (size=2)
0 =>
array (size=2)
0 => string 'one four-six nine twelve
zero eight nine ' (length=46)
1 => string 'one'
2 => string 'four'
3 => string 'six'
4 => string 'nine'
5 => string 'twelve'
6 => string 'zero'
7 => string 'eight'
8 => string 'nine'
1 =>
array (size=2)
0 => string 'nine seven three six six' (length=24)
...
更改代码以匹配您的所有号码,并添加名为号码的命名组:
<?php
$pattern = '/\b(?<number>one|two|three|four|five|(?:s|z)ix|seven|eight|nine|zero|twelve)(?:\s|-)/';
$subject = "one four-six nine twelve
zero eight nine nine seven three six six";
$matches = [];
preg_match_all ($pattern, $subject, $matches, PREG_SET_ORDER);
print_r($matches);
?>
这有十二个(全部)结果。请参阅regex101.com上的演示。更改了代码以匹配您的所有号码,并添加了名为号码的命名组:
<?php
$pattern = '/\b(?<number>one|two|three|four|five|(?:s|z)ix|seven|eight|nine|zero|twelve)(?:\s|-)/';
$subject = "one four-six nine twelve
zero eight nine nine seven three six six";
$matches = [];
preg_match_all ($pattern, $subject, $matches, PREG_SET_ORDER);
print_r($matches);
?>
这有十二个(全部)结果。请参阅regex101.com上的演示
我想看到的是,$matches
中所有分隔的单词
第一个字只有九个,第二个字只有六个
不幸的是,情况就是这样,正如所述:
重复捕获子模式时,捕获的值为
匹配最终迭代的子字符串
我知道我可以把所有的单字放在括号里,但还有其他的吗 好办法 一种方法是在以后分割找到的匹配项:
preg_match_all($pattern, $subject, $matches, PREG_SET_ORDER);
foreach ($matches as &$m)
// replace $m[1] with the split match
array_splice($m, 1, 1, preg_split('/\s|-/', $m[0], 0, PREG_SPLIT_NO_EMPTY));
unset($m); // remove the reference to the last element
这将在$matches
中产生所需的结果
我想看到的是,$matches
中所有分隔的单词
第一个字只有九个,第二个字只有六个
不幸的是,情况就是这样,正如所述:
重复捕获子模式时,捕获的值为
匹配最终迭代的子字符串
我知道我可以把所有的单字放在括号里,但还有其他的吗 好办法 一种方法是在以后分割找到的匹配项:
preg_match_all($pattern, $subject, $matches, PREG_SET_ORDER);
foreach ($matches as &$m)
// replace $m[1] with the split match
array_splice($m, 1, 1, preg_split('/\s|-/', $m[0], 0, PREG_SPLIT_NO_EMPTY));
unset($m); // remove the reference to the last element
这将在
$matches
中产生所需的结果。请详细说明您的预期输出。您正在寻找吗?没有。我按预期添加了输出请详细说明您的预期输出。您正在寻找吗?没有。我按预期添加了输出。不,它们从4分组到8是有原因的。不,它们从4分组到8是有原因的。