PHP:如何获取 preg_match_all 的字符串索引?
假设我有两个正则表达式
/eat (apple|pear)/
/I like/
和文本
"I like to eat apples on a rainy day, but on sunny days, I like to eat pears."
我想要的是使用 preg_match 获取以下索引:
match: 0,5 (I like)
match: 10,19 (eat apples)
match: 57,62 (I like)
match: 67,75 (eat pears)
有没有办法使用 preg_match_all 获取这些索引,而无需每次都循环遍历文本?
编辑:解决方案 PREG_OFFSET_CAPTURE!
let's say I have two regexp's,
/eat (apple|pear)/
/I like/
and text
"I like to eat apples on a rainy day, but on sunny days, I like to eat pears."
What I want is to get the following indexes with preg_match:
match: 0,5 (I like)
match: 10,19 (eat apples)
match: 57,62 (I like)
match: 67,75 (eat pears)
Is there any way to get these indexes using preg_match_all without looping through the text every single time?
EDIT: SOLUTION PREG_OFFSET_CAPTURE !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请记住,如果您使用
preg_match
,并且组不匹配,则不会返回数组,而是返回空字符串。您可以使用 T-Regx 并使用更干净的 API :或者如果你想要一些更高级的比赛
Please keep in mind that if you use
preg_match
, and a group isn't matched then not an array will be returned, but an empty string. You can use T-Regx and use cleaner API:Or if you want some more advanced matches
您可以尝试
preg_match() 的
:PREG_OFFSET_CAPTURE
标志输出
You can try
PREG_OFFSET_CAPTURE
flag forpreg_match()
:Output