Home > Backend Development > PHP Tutorial > How to Split a String by Multiple Delimiters in PHP?

How to Split a String by Multiple Delimiters in PHP?

Barbara Streisand
Release: 2024-11-03 10:03:03
Original
754 people have browsed it

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!"
Copy after login

To split this string by the ";" and "," delimiters, you would want to obtain the following result:

something here

and there

oh

that's all!
Copy after login
Copy after login

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

We then use this pattern to split the string using the following code:

$string = &quot;something here ; and there, oh,that's all!&quot;;

echo '<pre class="brush:php;toolbar:false">', print_r( preg_split( $pattern, $string ), 1 ), '</pre>';
Copy after login

The output of this code will be the desired split string:

something here

and there

oh

that's all!
Copy after login
Copy after login

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!

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