php 如何获取字符串中正则表达式匹配的位置?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9571231/
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
How to get the position of a Regex match in a string?
提问by johnnietheblack
I know how to use preg_match and preg_match_all to find the actual matches of regex patterns in a given string, but the function that I am writing not only needs the text of the matches, but to be able to traverse the string AROUND the matches...
我知道如何使用 preg_match 和 preg_match_all 来查找给定字符串中正则表达式模式的实际匹配项,但是我正在编写的函数不仅需要匹配项的文本,还需要能够遍历匹配项周围的字符串。 .
Therefore, I need to know the position of the match in the string, based on a regex pattern.
因此,我需要根据正则表达式模式知道匹配项在字符串中的位置。
I can't seem to find a function similar to strpos() that allows regex...any ideas?
我似乎找不到类似于 strpos() 的函数,它允许正则表达式......有什么想法吗?
回答by Linus Kleen
You can use the flag PREG_OFFSET_CAPTURE
for that:
您可以使用该标志PREG_OFFSET_CAPTURE
:
preg_match('/bar/', 'Foobar', $matches, PREG_OFFSET_CAPTURE);
var_export($matches);
Result is:
结果是:
array (
0 =>
array (
0 => 'bar',
1 => 3, // <-- the string offset of the match
),
)
In a previous version, this answer included a capture group in the regular expression (preg_match('/(bar)/', ...)
). As evident in the first few comments, this was confusing to some and has since been edited out by @Mikkel. Please ignore these comments.
在以前的版本中,此答案在正则表达式 ( preg_match('/(bar)/', ...)
) 中包含一个捕获组。从前几条评论中可以明显看出,这让一些人感到困惑,此后已被 @Mikkel 编辑掉。请忽略这些评论。
回答by Marc B
preg_match has an optional flag, PREG_OFFSET_CAPTURE
, that records the string position of the match's occurence in the original 'haystack'. See the 'flags' section: http://php.net/preg_match
preg_match 有一个可选标志 ,PREG_OFFSET_CAPTURE
它记录了匹配在原始 'haystack' 中出现的字符串位置。请参阅“标志”部分:http: //php.net/preg_match
回答by PoX
With use of PREG_OFFSET_CAPTURE on preg_match() you will get number of times on matches on pattern. When there is a match this will have the offset value which starts from 0.
通过在 preg_match() 上使用 PREG_OFFSET_CAPTURE,您将获得模式匹配的次数。当存在匹配时,这将具有从 0 开始的偏移值。
Using this value you can call preg_match again using offset parameter.
使用此值,您可以使用偏移参数再次调用 preg_match。