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
- Start with "abc", looking for a
- Do this Read the first byte offset
- Result 0
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.
<?php
declare(strict_types=1);
foreach (['SKU-47', 'item-47'] as $text) {
$position = strpos($text, 'SKU');
echo ($position === false ? 'missing' : (string) $position) . "\n";
}
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.
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.
<?php
$value = "CS-104";
$other = "-";
echo (strpos($value, $other)), PHP_EOL;
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.
<?php
$value = "A/B/C";
$other = "/";
echo (strpos($value, $other)), PHP_EOL;
1
The first slash comes immediately after A.