判断字符相邻并返回位置。
如:$str ='1110'; return 123
$str ='1101'; return 12
就是字符相邻并输出字符所在位置。下面是我自己写的,有没有更优化的方法。$str ='1101';
$arr=array();
$continue =0;for($i=0;$i<strlen($str);$i++){
if($str[$i]==1){
if($str[$i]==$str[++$i]){
if($continue==0){
$arr[] = $i;
}
$arr[] = $i+1;
--$i;
$continue =1;
}
}
}
print_r($arr);返回 :
Array
(
[0] => 1
[1] => 2
)
如:$str ='1110'; return 123
$str ='1101'; return 12
就是字符相邻并输出字符所在位置。下面是我自己写的,有没有更优化的方法。$str ='1101';
$arr=array();
$continue =0;for($i=0;$i<strlen($str);$i++){
if($str[$i]==1){
if($str[$i]==$str[++$i]){
if($continue==0){
$arr[] = $i;
}
$arr[] = $i+1;
--$i;
$continue =1;
}
}
}
print_r($arr);返回 :
Array
(
[0] => 1
[1] => 2
)
写个比较汎用的:
<?php
$str = 'abcccdefghhjj';
$arr = array();
$pos = -1;
while (++$pos<strlen($str)) {
if ($str[$pos]==$str[$pos+1])
$arr[] = $pos+1;
else if ($str[$pos]==$str[$pos-1])
$arr[] = $pos+1;
}
print_r($arr);
?>
$str2 = '1101';
preg_match_all('/1{2,}/', $str, $arr);
preg_match_all('/1{2,}/', $str2, $arr);
$str ='1101'; return 1,2
$str ='0011'; return 3,4
然后在emplode('000')
然后把有一的位置输出
$start = strpos($str,'11',0);
if (false === ($end = strpos($str,'0',$start))) {
$end = strlen($str);
}
return range(++$start,$end);
}
$newstr = implode ( "000", $strArray );
for ($i = 0;$i<=strlen($str); $++)
{
echo strpos($str,'1',$i);
}
$strArray = explode ( "010", $str );
$newstr = implode ( "000", $strArray );
for ($i = 0;$i <=strlen($str); $++)
{
echo strpos($newstr ,'1',$i);
}