Home >Backend Development >PHP Tutorial >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!