"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Explode a String with Multiple Delimiters in PHP?

How to Explode a String with Multiple Delimiters in PHP?

Published on 2024-11-18
Browse:536

How to Explode a String with Multiple Delimiters in PHP?

Php Multiple Delimiters in Explode

Exploding a string with multiple delimiters in PHP can be challenging. To address this, it is possible to define a custom function to perform the task. One such implementation is shown below:

private function multiExplode($delimiters,$string) {
    $ary = explode($delimiters[0],$string);
    array_shift($delimiters);
    if($delimiters != NULL) {
        if(count($ary) <2)                      
            $ary = $this->multiExplode($delimiters, $string);
    }
    return  $ary;
}

However, a more efficient solution is to utilize the preg_split() function. This function allows you to specify multiple delimiters by constructing a regular expression. For example:

$output = preg_split('/ (@|vs) /', $input);

This expression will split the input string on either the "@" or "vs" delimiters, resulting in an array with separate values.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3