Search code examples
phphexexplodestrtok

How can we separate string by only its starting characters in PHP


I am trying to separate a very long string which starting tag is 2424... This a function where its doing it

protected function StartTagCheckAndNeglect($hex)
       {
       try {

        $token = strtok($hex, "2424");

        while ($token !== false) {
            echo "$token<br>";
            $token = strtok("(2424)");
        }

    } catch (Exception $e) {
        echo $e->getMessage();
    }

}

$hex has very long hex string...THE PROBLEM IS instead of only separting string that start with 2424....it split any thing that start with 2 or 4. Example : 24246778672552dd455 It gives :4677867, 55, dd, 55 What i want is 6778672552dd455 in one string until next 2424.Any Better solution would be helpful.


Solution

  • A simple way would be to use explode() with 2424 as the delimiter. You can then check if the first element is empty (so there is nothing before the first 2424) and there are more than 1 elements (using count())...

    $test = "24246778672552dd4552424a123";
    
    $results = explode("2424", $test);
    if ( empty($results[0]) && count($results) > 1 )   {
        //found
        array_shift($results);   // Remove empty element
        print_r($results);
    }
    

    outputs...

    Array
    (
        [0] => 6778672552dd455
        [1] => a123
    )
    

    The problem with strtok() is that it will split the string based on ANY of the characters in your string, so it will split on either 2 or 4 and not 2424. From the manual...

    strtok() splits a string (str) into smaller strings (tokens), with each token being delimited by any character from token.