Home >Backend Development >PHP Tutorial >How to Explode a String with Multiple Delimiters in PHP?

How to Explode a String with Multiple Delimiters in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-11-02 06:31:30937browse

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:

<code class="php">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;
}</code>

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:

<code class="php">$output = preg_split('/ (@|vs) /', $input);</code>

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

The above is the detailed content of How to Explode a String with Multiple Delimiters in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn