我是php的新手。是否有任何函数可以匹配给定字符串中的模式,并返回该字符串中模式开头的索引?
例如:if $pattern = '/abcd/'
,$string = 'weruhfabcdwuir'
那么函数应该返回6,因为6是'abcd'
中$string
的索引{/ 1}}
答案 0 :(得分:5)
您可以使用strpos()
。
答案 1 :(得分:3)
如果您尝试匹配正则表达式(不是直字符串),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);