Home > Article > Backend Development > How to Split a String by Multiple Delimiters in PHP?
Splitting a String by Multiple Delimiters in PHP
When working with strings, there may be situations where you need to separate them into individual elements based on specific characters or delimiters. In PHP, you can split a string by multiple delimiters using the preg_split() function.
Problem Description
Consider the following string:
"something here ; and there, oh,that's all!"
To split this string by the ";" and "," delimiters, you would want to obtain the following result:
something here and there oh that's all!
Solution
To achieve the desired result, we can use the preg_split() function, which takes a regular expression pattern as its first argument and the string to be split as its second argument. In this case, we need a regular expression pattern that matches the ";" and "," characters:
<code class="php">$pattern = '/[;,]/';</code>
We then use this pattern to split the string using the following code:
$string = "something here ; and there, oh,that's all!";
echo '<pre class="brush:php;toolbar:false">', print_r( preg_split( $pattern, $string ), 1 ), '</pre>';
The output of this code will be the desired split string:
something here and there oh that's all!
The above is the detailed content of How to Split a String by Multiple Delimiters in PHP?. For more information, please follow other related articles on the PHP Chinese website!