[英]How to find the position of a pattern in a string using PHP?
我是php的新手。 是否有任何功能可以匹配给定字符串中的模式并返回该模式在该字符串中的开头的索引? 例如:如果$pattern = '/abcd/'
, $string = 'weruhfabcdwuir'
则该函数应返回6,因为6是$string
中'abcd'
起始索引
您可以为此使用strpos()
。
如果您尝试匹配一个正则表达式模式(不是直串),则strpos()
将无济于事。 相反,请使用preg_match()
(如果您只想在第一个匹配项上进行匹配)或preg_match_all()
(如果要匹配所有匹配项)和PREG_OFFSET_CAPTURE
标志:
$pattern = '/abcd/';
$string = 'weruhfabcdwuir';
preg_match($pattern, $string, $matches, PREG_OFFSET_CAPTURE);
// $matches[0][0][1] == 6, see PHP.net for structure of $matches
print_r($matches);
使用preg_match_all()
进行多个匹配的示例:
$pattern = '/abcd/';
$string = 'weruhfabcdwuirweruhfabcdwuir';
preg_match_all($pattern, $string, $matches, PREG_OFFSET_CAPTURE);
// $matches[0][0][1] == 6
// $matches[0][1][1] == 20
print_r($matches);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.