如何使用PHP在字符串中找到模式的位置?

时间:2011-02-28 05:04:34

标签: php

我是php的新手。是否有任何函数可以匹配给定字符串中的模式,并返回该字符串中模式开头的索引? 例如:if $pattern = '/abcd/'$string = 'weruhfabcdwuir'那么函数应该返回6,因为6是'abcd'$string的索引{/ 1}}

2 个答案:

答案 0 :(得分:5)

答案 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);