Home > Article > Backend Development > How to Split a String with Multiple Delimiters in PHP?
Splitting Strings with Multiple Delimiters in PHP
In PHP, splitting a string into smaller parts by using multiple delimiters is a straightforward process. Suppose you have a string like:
"something here ; and there, oh,that's all!"
And you want to split it into a list of strings, separating the parts by ";" and ",". You can achieve this using the preg_split() function.
$pattern = '/[;,]/';
$string = "something here ; and there, oh,that's all!";
$split = preg_split( $pattern, $string );
print_r( $split ); // Output: Array
In this code, the $pattern defines the delimiters to split by, in this case, ";" and ",". The preg_split() function then divides the $string into individual substrings based on the specified pattern. The resulting array, $split, contains the separated substrings:
[ "something here", "and there", "oh", "that's all!" ]
This demonstrates how you can effectively split a string by multiple delimiters in PHP. The use of the preg_split() function and a well-defined delimiter pattern allows you to efficiently work with strings and extract specific parts of text based on the desired separators.
The above is the detailed content of How to Split a String with Multiple Delimiters in PHP?. For more information, please follow other related articles on the PHP Chinese website!