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

How to Split a String Using Multiple Delimiters in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-11-04 04:59:29440browse

How to Split a String Using Multiple Delimiters in PHP?

Separation of Strings Using Multiple Delimiters in PHP

In PHP, splitting strings by multiple delimiters is a common task that requires a tailored approach. Let's consider an example:

<code class="php">$string = "something here ; and there, oh,that's all!";
// Split the string by ";" and "," delimiters</code>

How can we achieve this? The solution lies in utilizing PHP's preg_split() function, which allows for splitting based on regular expressions.

<code class="php">$pattern = '/[;,]/';

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

In this example, the regular expression /[;,]/ matches any occurrence of either a semicolon (;) or a comma (,):

  • / denotes the beginning and end of the regular expression.
  • [;,] matches a literal semicolon or comma.
  • The [] square brackets create a character class that captures either character.
  • The . metacharacter matches any character that isn't a newline.
  • The * quantifier indicates that the pattern can match zero or more occurrences.

As a result, the function splits the input string into multiple lines:

something here

and there

oh

that's all!

This technique provides a versatile solution for splitting strings by multiple delimiters in PHP.

The above is the detailed content of How to Split a String Using Multiple Delimiters in PHP?. 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