我需要在字符串中找到特定字符的所有位置。我正在使用以下代码
$pos = 0;
$positions = array();
while( $pos = strpos($haystack,$needle,$pos){
$positions[] = $pos;
$pos = $pos+1;
}
此代码的问题在于,当needle
位于位置 1 时,它返回 1,因此不会进入循环。
所以我尝试了以下方法
$pos = 0;
$positions = array();
while( ($pos = strpos($haystack,$needle,$pos) || (strpos($haystack,$needle,$pos)=== 0){
$positions[] = $pos;
$pos = $pos+1;
}
和
$pos = 0;
$positions = array();
while( ($pos = strpos($haystack,$needle,$pos) || (strpos($haystack,$needle,$pos) != false){
$positions[] = $pos;
$pos = $pos+1;
}
但似乎没有任何效果。有没有其他办法。
我尝试过的两种选择给了我
Allowed memory size of 268435456 bytes exhausted
我认为这与编程错误有关,而不是内存问题。
请帮忙。
您需要
使用!==
而不是!=
因为零被认为是假的,因此您还需要按类型进行比较:
while($pos = (strpos($haystack,$needle,$pos) !== false){
$positions[] = $pos;
$pos++;
}
编辑
从注释中查看代码的工作版本:
$positions = array();
while( ($pos = strpos('lowly','l',$pos)) !== false){
$positions[] = $pos;
$pos++;
}
print_r($positions);
看到它在这里工作。
使用此代码。
$start = 0;
while ($pos = strpos($string, ',', $start) !== FALSE) {
$count++;
$start = $pos + 1;
}