Home  >  Article  >  Backend Development  >  How to Split a String in PHP with Multiple Delimiters?

How to Split a String in PHP with Multiple Delimiters?

Susan Sarandon
Susan SarandonOriginal
2024-11-03 14:40:31997browse

How to Split a String in PHP with Multiple Delimiters?

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!

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