php preg 比赛计数比赛
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3064106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
preg match count matches
提问by Scarface
I have a preg match statement, and it checks for matches, but I was wondering how you can count the matches. Any advice appreciated.
我有一个 preg match 语句,它检查匹配,但我想知道如何计算匹配。任何建议表示赞赏。
$message='[tag] [tag]';
preg_match('/\[tag]\b/i',$message);
for example a count of this message string should lead to 2 matches
例如,此消息字符串的计数应导致 2 个匹配项
回答by Artefacto
$message='[tag] [tag]';
echo preg_match_all('/\[tag\](?>\s|$)/i', $message, $matches);
gives 2. Note you cannot use \bbecause the word boundary is before the ], not after.
给2. 请注意,您不能使用,\b因为单词边界在 之前],而不是之后。
See preg_match_all.
回答by webbiedave
preg_matchalready returns the number of times the pattern matched.
preg_match已经返回模式匹配的次数。
However, this will only be 0 or 1 as it stops after the first match. You can use preg_match_allinstead as it will check the entire string and return the total number of matches.
但是,这只会是 0 或 1,因为它会在第一场比赛后停止。您可以改用preg_match_all ,因为它会检查整个字符串并返回匹配的总数。
回答by Matěj G.
You should use preg_match_allif you want to match all occurences. preg_match_allreturns number of matches. preg_matchreturns only 0 or 1, because it matches only once.
preg_match_all如果要匹配所有出现,则应使用。preg_match_all返回匹配数。preg_match只返回 0 或 1,因为它只匹配一次。
回答by Manos Dilaverakis
I think you need preg_match_all. It returns the number of matches it finds. preg_match stops after the first one.
我认为你需要preg_match_all。它返回它找到的匹配数。preg_match 在第一个之后停止。
回答by Danon
You could use T-Regx librarywith count()method (and even automatic delimiters):
您可以将T-Regx 库与count()方法(甚至自动分隔符)一起使用:
$count = pattern('\[tag]\b', 'i')->match('[tag] [tag]')->count();
$count // 2

