Search code examples
phparraysstringsplitunset

How do i unset duplicate string in a str_split string line


How do i check if same string occurs twice or multiples times and remove it. Example the split string is 123 456 123 789, I want to be able to unset the repeated character in the split string line example my expected output should be like web123 web456 web789. Here is what I tried:

<?php

$str = "jmja12345jmja612378911";
$int = filter_var($str, FILTER_SANITIZE_NUMBER_INT);
$disp = str_split($int, 3);
foreach($disp as $char){
    if(strlen($char) == "3") 
    {
        $net = substr($char,1,2);
        if(preg_match('/(50|30)/i', $net))
        {
            echo "our computer can not edit $net";
            exit();
        }
        else
        {
            $pd = str_replace("$net","web$net",$net);
            $str = implode(array_unique(explode( $pd)));
            echo $str;
        }
    }
}

But I get no good result. What am I doing wrong? view at https://ideone.com/fork/rGyH41


Solution

  • if you just need to remove the duplicate values . why you not try it directly like this .

    <?php
    
    $str = "jmja12345jmja612378911";
    $int = filter_var($str, FILTER_SANITIZE_NUMBER_INT);
    $disp = str_split($int, 3);
    $arr = array_unique($disp);
    var_dump($arr);
    

    and for your function to work . try this

    $str = "jmja12345jmja612378911";
    $int = filter_var($str, FILTER_SANITIZE_NUMBER_INT);
    $disp = str_split($int, 3);
    foreach($disp as $char){
        if(strlen($char) == "3") 
        {
            $net = substr($char,1,2);
            if(preg_match('/(50|30)/i', $net))
            {
                echo "our computer can not edit $net";
                exit();
            }
            else
            {
                $pd[] = str_replace("$net","web$net",$net);
            }
        }
    }
    
    $array = array_values(array_unique($pd));
    var_dump($array);
    $str = implode(array_unique($pd));
    echo $str;