获取小组中所有比赛的位置
考虑以下示例:
$target = 'Xa,a,aX';
$pattern = '/X((a),?)*X/';
$matches = array();
preg_match_all($pattern,$target,$matches,PREG_OFFSET_CAPTURE|PREG_PATTERN_ORDER);
var_dump($matches);
它所做的只是返回系列中的最后一个“a”,但我需要的是所有“a”。
特别是,我需要字符串中 ALL EACH OF 'a 的位置单独,因此 PREG_OFFSET_CAPTURE。
该示例要复杂得多,请参阅相关问题: 模式匹配一个数组,而不是它们的元素本身
谢谢
Consider the following example:
$target = 'Xa,a,aX';
$pattern = '/X((a),?)*X/';
$matches = array();
preg_match_all($pattern,$target,$matches,PREG_OFFSET_CAPTURE|PREG_PATTERN_ORDER);
var_dump($matches);
What it does is returning only the last 'a' in the series, but what I need is all the 'a's.
Particularly, I need the position of ALL EACH OF the 'a's inside the string separately, thus PREG_OFFSET_CAPTURE.
The example is much more complex, see the related question: pattern matching an array, not their elements per se
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于正则表达式
X((a),?)*X
匹配整个字符串,因此它将单个匹配项分组。最后一个((a),?)
将被分组。您想要匹配的是一个
a
,它前面有一个X
(以及字符串的开头),前面有一个逗号,或者有一个X
位于其前面(以及字符串的末尾)。输出:
It groups a single match since the regex
X((a),?)*X
matches the entire string. The last((a),?)
will be grouped.What you want to match is an
a
that has anX
before it (and the start of the string), has a comma ahead of it, or has anX
ahead of it (and the end of the string).Output:
当您的正则表达式包含 X 时,它会匹配一次。它找到了一场包含组的大型比赛。你想要的是很多场比赛,每场比赛都有自己的位置。
所以,在我看来,你能做的最好的事情就是简单地搜索 /a/ 或 /a,?/ 而不带任何 X。然后 matches[0] 将包含所有出现的 'a'
如果你需要它们在 X 之间,请预先选择字符串的这一部分。
When your regex includes X, it matches once. It finds one large match with groups in it. What you want is many matches, each with its own position.
So, in my opinion the best you can do is simply search for /a/ or /a,?/ without any X. Then matches[0] will contain all appearances of 'a'
If you need them between X, pre-select this part of the string.