How to Split a String in PHP with Multiple Delimiters?

Susan Sarandon
Release: 2024-11-03 14:40:31
Original
996 people have browsed it

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

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!