Preg_match_all 在数组中返回数组?

发布于 2024-11-08 05:14:49 字数 406 浏览 2 评论 0原文

我试图从该数组中获取信息,但由于某种原因,它将所有内容都嵌套到 $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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

野却迷人 2024-11-15 05:14:49

preg_match_all() 始终返回一个数组(如果成功,否则会得到一个空数组),其中索引 0 包含一个数组,其中包含每个完整匹配的元素,其他索引成为捕获组,每场比赛都有一个内部数组。

这样可能更容易理解...

array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(12) "entire match"
    [1]=>
    string(32) "entire match matched second time"
  }
  [1]=>
  array(2) {
    [0]=>
    string(15) "capturing group"
    [1]=>
    string(35) "capturing group matched second time"
  }
}

preg_match_all() always returns an array (if successful, otherwise you get an empty array) where index 0 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...

array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(12) "entire match"
    [1]=>
    string(32) "entire match matched second time"
  }
  [1]=>
  array(2) {
    [0]=>
    string(15) "capturing group"
    [1]=>
    string(35) "capturing group matched second time"
  }
}
满栀 2024-11-15 05:14:49

如果您的目标是仅获取捕获的字符(由“([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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文