PHP preg_match仅返回第一个匹配项 [英] PHP preg_match returns only first match

查看:266
本文介绍了PHP preg_match仅返回第一个匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 第一个问题是

我正在使用 http://www.phpliveregex.com/来检查我的正则表达式是否正确,找到多个匹配的行.

I am using http://www.phpliveregex.com/ to check my regex is right and it finds more than one matching lines.

我正在执行此正则表达式:

I am doing this regex:

$lines = explode('\n', $text);
foreach($lines as $line) {
    $matches = [];
    preg_match("/[0-9]+[A-Z][a-z]+ [A-Z][a-z]+S[0-9]+\-[0-9]+T[0-9]+/uim", $line, $matches);

    print_r($matches);
}

$text上的

如下所示: http://pastebin.com/9UQ5wNRu

问题在于,印刷的火柴只有一种火柴:

The problem is that printed matches is only one match:

Array
(
     [0] => 3Bajus StanislavS2415079249-2615T01
)

为什么对我这样做?有什么想法可以解决问题吗?

Why is it doing to me? any ideas what could fix the problem?

  1. 第二个问题

也许您没有注意到文本内部(来自pastebin)斯洛伐克语言的常规字母字符.如何匹配这些字符并选择具有以下格式的用户:

Maybe you've noticed not regular alphabetic characters of slovak language inside the text (from pastebin). How to match those characters and select the users which have this format:

{number}{first_name}{space}{last_name}{id_number}

该怎么做?

确定的第一个问题已修复.谢谢@ chris85.我应该使用preg_match_all并在全文中使用它.现在,我得到了所有名称中都包含非斯洛伐克语(英语)字母的学生的数组.

Ok first issue is fixed. Thank you @chris85 . I should have used preg_match_all and do it on the whole text. Now I get an array of all students which have non-slovak (english) letters in the name.

推荐答案

preg_match适用于一场比赛.您需要使用preg_match_all进行全局搜索.

preg_match is for one match. You need to use preg_match_all for a global search.

[A-Z]不包含超出该范围的字符.由于您使用的是i修饰符,因此实际的字符类是[A-Za-z],可能不是您想要的.您可以使用\p{L}代替任何语言的字符.

[A-Z] does not include an characters outside that range. Since you are using the i modifier that character class actual is [A-Za-z] which may or may not be what you want. You can use \p{L} in place of that for characters from any language.

演示: https://regex101.com/r/L5g3C9/1

所以您的PHP代码就是:

So your PHP code just be:

preg_match_all("/^[0-9]+\p{L}+ \p{L}+S[0-9]+\-[0-9]+T[0-9]+$/uim", $text, $matches);
print_r($matches);

这篇关于PHP preg_match仅返回第一个匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆