如果有连续相似的字符串,则只打印一个字符串

时间:2016-07-18 07:31:19

标签: php string loops

我有一个变量$ b = substr($ r ['pon_port'],4,2);在foreach循环中。 $ b的Var转储给出了这样的字符串列表:

string(1) "0" string(1) "0" string(1) "0" string(1) "0" string(1) "0"
string(1) "1" string(1) "1" string(1) "1" string(1) "1" string(1) "1"
string(1) "2" string(1) "2" string(1) "2" string(1) "2" string(1) "2"
string(1) "3" string(1) "3" string(1) "3" string(1) "3" string(1) "3"
string(1) "4" string(1) "4" string(1) "4" string(1) "4" string(1) "4"
string(1) "0" string(1) "0" string(1) "0" string(1) "0" string(1) "0"
string(1) "1" string(1) "1" string(1) "1" string(1) "1" string(1) "1"

我想要的是如果有类似的连续字符串我想只有一个字符串>例如:在上面的转储中。我只想要:

string(1) "0" 
string(1) "1" 
string(1) "2" 
string(1) "3" 
string(1) "4" 
string(1) "0" 
string(1) "1" 

2 个答案:

答案 0 :(得分:0)

如果我理解正确,你可以记住最后一个数字:

$lastB = null;
foreach ($foo as $r) //I'm guessing that $r is the dummy variable, based on your code
{
        $b = substr($r['pon_port'],4,2); //You wrote this

        //This part prevents repetitions from happening
        if ($lastB === null || $b != $lastB) var_dump($lastB = $b);
}

(在这种情况下,我使用var_dump($lastB = $b)而不是两个单独的语句将作业隐藏到参数中。我发现它更整洁,但如果您愿意,可以将它们分开。)

如果您想要打印变量以外的其他操作,最终结果可以使用此代码:

$lastB = null;
foreach ($foo as $r) //I'm guessing that $r is the dummy variable, based on your code
{
        $b = substr($r['pon_port'],4,2); //You wrote this

        //This part prevents repetitions from happening
        if ($lastB === null || $b != $lastB)
        {
            //do something with $b...
            $lastB = $b;
        }
}

在序列“2 2 7 8 8 7”上自己尝试第一个代码,我得到:

string(1) "2" string(1) "7" string(1) "8" string(1) "7"

答案 1 :(得分:0)

基于背景的我(可能是愚蠢的)假设是它们总是单位数字。你可以1行,但为了便于阅读:

$nums = array(0,0,1,2,2,3,4,0,1,2,2,1,2,1,2,3,3,4,4,4);
print_r($nums);
$nums = implode('',$nums);
$nums = preg_replace('~(\d)((?=\1).)+~','$1',$nums);
$nums = str_split($nums);
print_r($nums)

输出:

Array
(
    [0] => 0
    [1] => 0
    [2] => 1
    [3] => 2
    [4] => 2
    [5] => 3
    [6] => 4
    [7] => 0
    [8] => 1
    [9] => 2
    [10] => 2
    [11] => 1
    [12] => 2
    [13] => 1
    [14] => 2
    [15] => 3
    [16] => 3
    [17] => 4
    [18] => 4
    [19] => 4
)

Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4
    [5] => 0
    [6] => 1
    [7] => 2
    [8] => 1
    [9] => 2
    [10] => 1
    [11] => 2
    [12] => 3
    [13] => 4
)