如何获得正则表达式匹配在字符串中的位置? [英] How to get the position of a Regex match in a string?

查看:1186
本文介绍了如何获得正则表达式匹配在字符串中的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何使用preg_match和preg_match_all查找给定字符串中的正则表达式模式的实际匹配项,但是我编写的函数不仅需要匹配项的文本,还需要能够遍历字符串匹配...

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...

因此,我需要根据正则表达式模式了解匹配在字符串中的位置.

Therefore, I need to know the position of the match in the string, based on a regex pattern.

我似乎找不到类似于strpos()的允许正则表达式的函数...任何想法吗?

I can't seem to find a function similar to strpos() that allows regex...any ideas?

推荐答案

您可以使用标志

You can use the flag PREG_OFFSET_CAPTURE for that:

preg_match('/bar/', 'Foobar', $matches, PREG_OFFSET_CAPTURE);
var_export($matches);

结果是:

array (
  0 => 
  array (
    0 => 'bar',
    1 => 3,     // <-- the string offset of the match
  ),
)


在以前的版本中,此答案在正则表达式(preg_match('/(bar)/', ...))中包含捕获组.从前几条评论中可以明显看出,这使某些人感到困惑,此后已由@Mikkel进行了编辑.请忽略这些评论.


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.

这篇关于如何获得正则表达式匹配在字符串中的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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