Library contents

PHP strpos

strpos returns the byte offset of the first occurrence of a substring or false when there is no match.

A simple example

strpos

  1. Start with "abc", looking for a
  2. Do this Read the first byte offset
  3. Result 0
The first character begins at byte zero. Zero is a successful match here.

Syntax

PHP syntax
$position = strpos($text, $needle)
Run this example in PHP

Save the program as lesson.php. Use PHP 8.2 or later.

php lesson.php

Find a prefix match at byte position zero

A scanned code can start with a standard prefix that the receiving system handles separately. Test that position before extracting or moving the characters that belong to the actual identifier.

From the programdeclare(strict_types=1)
First output line0
lesson.php
<?php
declare(strict_types=1);

foreach (['SKU-47', 'item-47'] as $text) {
    $position = strpos($text, 'SKU');
    echo ($position === false ? 'missing' : (string) $position) . "\n";
}
Output
0
missing

Compare the result strictly with false. A match at the first byte returns integer zero, which is false in a loose boolean test.

PHP documentation for strpos

Advertisements

Locate the hyphen in a classroom code

A compound filename or route code uses punctuation to separate fields. Decide whether the first or last separator marks the desired boundary before extracting the field next to it.

From the program$value = "CS-104"
Result2
lesson.php
<?php
$value = "CS-104";
$other = "-";
echo (strpos($value, $other)), PHP_EOL;
Output
2

The hyphen follows the two letters CS.

Find the first separator on a route

A route string contains several stops separated by the same punctuation. Find the first separator to locate the end of the starting stop before the remaining route is processed.

From the program$value = "A/B/C"
Result1
lesson.php
<?php
$value = "A/B/C";
$other = "/";
echo (strpos($value, $other)), PHP_EOL;
Output
1

The first slash comes immediately after A.