bhylu.com

Advertisements

PHP String Search

A text search often returns a position or a special failure value. Preserve that distinction before using the result to slice or branch.

How it works

strpos returns an integer byte offset or false. A match at the start therefore requires a strict false comparison. str_contains, str_starts_with and str_ends_with express boolean questions more directly when no offset is needed. Case-insensitive searching and Unicode case handling have separate API contracts. Pick the operation that answers the question without hiding a second conversion step.

Run it locally

Run this complete source locally with PHP 8.2 or newer. Save it using the filename shown and run the command below. PHP is not currently available in Bhylu’s browser playground. Apache and MySQL are not needed for an ordinary CLI example.

php -l string-search.php
php string-search.php

Download this source as a local PHP lab file. Keep lab files separate from the Bhylu project and production data.

Example

PHP 8.2+ · string-search.php

<?php
declare(strict_types=1);

$reference = "LOAN-204";
$position = strpos($reference, "LOAN");
echo $position !== false ? "Prefix found at $position\n" : "Not found\n";
echo str_starts_with($reference, "LOAN-") ? "Expected prefix\n" : "Other prefix\n";
echo substr($reference, 5), "\n";

Expected result

Prefix found at 0
Expected prefix
204

The search succeeds at byte zero. After confirming the expected ASCII prefix, the fixed byte slice extracts the numeric-looking suffix as text. It still needs validation if it is meant to become an integer ID. A search hit alone does not prove that the entire reference follows the required format.

Check the official PHP manual for detailed version and API contracts.