Lesson contents

PHP — Parsing strings with explode and trim

PHP explode with a limit of two separates a setting at its first equals sign. Check for both fields before using trim to remove their surrounding whitespace.

A simple example

Split one line of text

  1. Start with "a=b"
  2. Do this Separate at =
  3. Result b
The separator marks where the first field ends and the second begins. Read the second field.
lesson.php
<?php
$parts = explode("=", "a=b");
echo $parts[1], PHP_EOL;
Output
b
Advertisements

Split one setting into a key and a value

explode with a limit of two splits only at the first equals sign. Array destructuring assigns both pieces after the count check. trim removes surrounding whitespace.

Saved line: city = Lima. Setting name: city. Display value: Lima.
Read a destination from a settings file

A noticeboard reads its city from a saved setting. Split the line at its first equals sign and trim the spaces around the two fields. The board can now look up city and display Lima.

Run the example

PHP 8 or later. Run these commands from the directory containing the example.

php lesson.php
lesson.php
<?php
declare(strict_types=1);

$parts = explode('=', ' city = Lima ', 2);
if (count($parts) === 2) {
    [$key, $value] = $parts;
    echo trim($key), '=', trim($value), PHP_EOL;
}
Output
city=Lima

The input contains padding around city and Lima. Locating the first separator identifies the two fields. Trimming their ends gives city=Lima without changing text inside the value.

Try it yourself

What should city = A=B produce?

Check your answer

The value retains its second equals sign. The normalized line is city=A=B. Decide separately whether an empty key is valid for your file format.

PHP language reference

Related tags

  • PHP
  • strings
  • parsing
  • whitespace