PHP explode
explode splits text on a literal separator. A positive limit of two keeps further separators inside the second piece.
A simple example
explode
- Start with "a=b"
- Do this Split at the first equals sign
- Result Left a, right b
Syntax
$parts = explode('=', $field, 2)
Run this example in PHP
Save the program as lesson.php. Use PHP 8.2 or later.
php lesson.php
Preserve the rest of a configuration value
A configuration line separates a key from its value with punctuation. Split only at the first intended boundary because the value itself may contain the same separator later on.
<?php
declare(strict_types=1);
foreach (['token=a=b', 'mode=', 'broken'] as $field) {
$parts = explode('=', $field, 2);
if (count($parts) === 1) {
echo "missing separator\n";
continue;
}
printf("%s [%s]\n", $parts[0], $parts[1]);
}
token [a=b] mode [] missing separator
Count the resulting parts before reading the value. An empty second part is a present but empty value, while a missing separator gives just one part.
Count stops in a shuttle record
A timetable or route import divides each record at separators. Test the behavior at an empty field so later columns do not shift when the writer leaves a value blank.
<?php
$value = "Gate,Lab,Hall";
echo (count(explode(",", $value))), PHP_EOL;
3
Three nonempty stop fields are present.
Handle an express route
A transit editor changes selected text in a route while preserving its remaining stops or punctuation. Identify which occurrences belong to the requested edit before rebuilding the public route label.
<?php
$value = "Depot";
echo (count(explode(",", $value))), PHP_EOL;
1
With no delimiter the complete route is one field.