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

How to Split a String with Multiple Delimiters in PHP?

Barbara Streisand
Release: 2024-11-03 07:55:03
Original
705 people have browsed it

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

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

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

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!

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