Search code examples
phpspecial-charactersexplode

To explode the string based on the special characters in Php


I have a string:

xyz.com?username="test"&pwd="test"@score="score"#key="1234"

output format:

array (
    [0] => username="test"
    [1] => pwd="test"
    [2] => score="score"
    [3] => key="1234"
)

Solution

  • This should work for you:

    Just use preg_split() with a character class with all delimiters in it. At the end just use array_shift() to remove the first element.

    <?php
    
        $str = 'xyz.com?username="test"&pwd="test"@score="score"#key="1234"';
    
        $arr = preg_split("/[?&@#]/", $str);
        array_shift($arr);
    
        print_r($arr);
    
    ?>
    

    output:

    Array
    (
        [0] => username="test"
        [1] => pwd="test"
        [2] => score="score"
        [3] => key="1234"
    )