Library contents

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

  1. Start with "a=b"
  2. Do this Split at the first equals sign
  3. Result Left a, right b
The equals sign marks the boundary between the two fields.

Syntax

PHP 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.

From the programdeclare(strict_types=1)
First output linetoken [a=b]
lesson.php
<?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]);
}
Output
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.

PHP documentation for explode

Advertisements

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.

From the program$value = "Gate,Lab,Hall"
Result3
lesson.php
<?php
$value = "Gate,Lab,Hall";
echo (count(explode(",", $value))), PHP_EOL;
Output
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.

From the program$value = "Depot"
Result1
lesson.php
<?php
$value = "Depot";
echo (count(explode(",", $value))), PHP_EOL;
Output
1

With no delimiter the complete route is one field.