繁体   English   中英

混合preg_match,锚点和偏移量

[英]Mix preg_match, anchor and offset

我有$string = "hello world, world!"; 我只需匹配第一个 world ,所以我也有一个偏移 它从第6个角色开始。 preg_match()有五个参数:字符串模式 ,字符串主题 ,引用数组匹配,int标志和int 偏移量

我的模式是: $pattern = "/^world/";

如果我做preg_match($pattern, $string, $string_match, 0, 6) ,基本上我希望这有效,因为“anchor”会检查我的字符串的第6个字母,因为我设置了偏移量。 但不是! 它不起作用。 哦!

一个简单的解决方法是,而不是我为preg_match()函数设置偏移量,我在$string使用substr() ,就像它: preg_match($pattern, substr($string, 6), $string_match)

是否可以修复我的第一个代码以正确使用带有preg_match()偏移量的锚点? 或者它是独特的解决方案?

你使用错误的锚; 用偏移来玩你需要\\G ,最后一个匹配位置锚:

$string = 'hello world, world!';

var_dump(preg_match('/\Gworld/', $string, $matches, 0, 6)); // int(1)

有趣的是, 文档声明\\G不受支持,但自4.3.3以来,它肯定得到了可靠的支持

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM