2011-02-28 87 views

回答

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); 
相關問題