How to Explode a String with Multiple Delimiters in PHP?

Susan Sarandon
Release: 2024-11-02 06:31:30
Original
933 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template