0
0
PHPprogramming~5 mins

Preg_split for splitting in PHP

Choose your learning style9 modes available
Introduction
Preg_split helps you break a string into parts using patterns, not just simple characters. It is useful when you want to split text by complex rules.
You want to split a sentence by spaces, commas, or dots all at once.
You need to separate words but ignore multiple spaces or tabs.
You want to split a string by any number of digits or special characters.
You want to split text by a pattern like email addresses or hashtags.
You want to split a string but keep some parts or remove empty pieces.
Syntax
PHP
preg_split(string $pattern, string $subject, int $limit = -1, int $flags = 0): array
The $pattern is a regular expression enclosed in delimiters, like '/pattern/'.
The $limit controls how many pieces you get; -1 means no limit.
Examples
Splits the string by commas into an array of fruits.
PHP
$parts = preg_split('/,/', 'apple,banana,orange');
Splits by one or more spaces, so multiple spaces count as one separator.
PHP
$parts = preg_split('/\s+/', 'one  two   three');
Splits by comma or dot characters.
PHP
$parts = preg_split('/[,.]/', 'red,green.orange');
Splits by one or more digits.
PHP
$parts = preg_split('/\d+/', 'abc123def456ghi');
Sample Program
This program splits the string by commas, semicolons, or dots, ignoring spaces around them, and prints each fruit on a new line.
PHP
<?php
$text = "apple, banana; orange.pear";
// Split by comma, semicolon, or dot with optional spaces
$parts = preg_split('/\s*[,;.]+\s*/', $text);
foreach ($parts as $part) {
    echo $part . "\n";
}
?>
OutputSuccess
Important Notes
preg_split uses regular expressions, so learning simple regex helps a lot.
You can use flags like PREG_SPLIT_NO_EMPTY to skip empty parts in the result.
Remember to escape special characters in the pattern if needed.
Summary
preg_split splits strings using patterns, not just fixed characters.
It is useful for complex splitting rules like multiple separators or spaces.
You get an array of parts after splitting, which you can use in your program.