Preg_match_all 在数组中返回数组?
我试图从该数组中获取信息,但由于某种原因,它将所有内容都嵌套到 $matches[0]
中。
<?
$file = shell_exec('pdf2txt.py docs/April.pdf');
preg_match_all('/.../',$file,&$matches);
print_r($matches)
?>
这是否按预期工作?有没有办法将其放入深度为 1 的数组中?
编辑:
这是正则表达式:
([A-Z][a-z]+\s){1,5}\s?[^a-zA-Z\d\s:,.\'\"]\s?[A-Za-z+\W]+\s[\d]{1,2}\s[A-Z][a-z]+\s[\d]{4}
I am trying to get the information out of this array, but for some reason it is nesting everything into $matches[0]
.
<?
$file = shell_exec('pdf2txt.py docs/April.pdf');
preg_match_all('/.../',$file,&$matches);
print_r($matches)
?>
Is this working as intended? Is there a way to put this in an array of depth 1?
EDIT:
This is the RegEx:
([A-Z][a-z]+\s){1,5}\s?[^a-zA-Z\d\s:,.\'\"]\s?[A-Za-z+\W]+\s[\d]{1,2}\s[A-Z][a-z]+\s[\d]{4}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
preg_match_all()
始终返回一个数组(如果成功,否则会得到一个空数组),其中索引0
包含一个数组,其中包含每个完整匹配的元素,其他索引成为捕获组,每场比赛都有一个内部数组。这样可能更容易理解...
preg_match_all()
always returns an array (if successful, otherwise you get an empty array) where index0
contains an array with an element for each entire match, and the other indexes become the capturing groups, with an internal array for each match.This might be easier to understand...
如果您的目标是仅获取捕获的字符(由“([AZ][az]+\s){1,5}”捕获的字符),您应该查看 $matches[1] 内部。 $matches[1][0] 包含第一个捕获的字符序列。
根据 preg_match_all 文档,如果没有指定订单标志(如在您的示例中),假定为 PREG_PATTERN_ORDER。使用此模式,您会发现 $matches[0] 是一个数组,其中包含与完整模式匹配的所有字符串,而 $matches[1] 包含正则表达式捕获的字符串数组。
If your objective is to obtain only the captured characters (what was captured by your "([A-Z][a-z]+\s){1,5}") you should look inside $matches[1]. $matches[1][0] contains the first captured character sequence.
Per the preg_match_all docs, if no order flag is specified (as in your example), PREG_PATTERN_ORDER is assumed. Using this pattern, you'll find that $matches[0] is an array, which contains all strings that matched your full pattern, and $matches[1] contains an array of strings captured by your regex.