Exploding Strings with Multiple Delimiters in PHP
Exploding a string into an array is a common task in PHP. However, what if you need to split the string based on multiple delimiters?
Consider the example:
$example = 'Appel @ Ratte'; $example2 = 'apple vs ratte'
You want to explode these strings at either '@' or 'vs' to obtain an array with the split values.
One solution is to use a recursive function like the one provided in the question. However, there is a more efficient approach using regular expressions:
$output = preg_split('/ (@|vs) /', $input);
This regular expression will split the string at any occurrence of either '@' or 'vs', regardless of whether there is whitespace around the delimiter. The () delimit the delimiter pattern, and the | separates the two options.
For example:
$output = preg_split('/ (@|vs) /', $example); // Result: ['Appel', 'Ratte'] $output = preg_split('/ (@|vs) /', $example2); // Result: ['apple', 'ratte']
The above is the detailed content of How to Split a String in PHP with Multiple Delimiters?. For more information, please follow other related articles on the PHP Chinese website!