PHP strrpos
Find the final separator when a label contains several parts.
A simple example
strrpos
- Start with "aba", looking for a
- Do this Find the last match
- Result Index 2 (zero-based)
<?php
$value = "aba";
$other = "a";
echo (strrpos($value, $other)), PHP_EOL;
2
Syntax
strrpos($value, $other)
Run these examples in PHP
Save one example at a time as lesson.php. Use PHP 8.2 or later.
php lesson.phpFind the final dot in an archive name
An archive name contains more than one period. Locate the final one before extracting the extension so the earlier punctuation in the basename is preserved.
<?php
$value = "may.bill.pdf";
$other = ".";
echo (strrpos($value, $other)), PHP_EOL;
8
The dot before pdf is the last match.
Find the last route separator
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 = "A/B/C";
$other = "/";
echo (strrpos($value, $other)), PHP_EOL;
3
The final slash comes before stop C.
Read a parcel sorting code
The depot scans a parcel marked NC-17. Find the dash in this identifier. How many characters precede the matching separator?
What to watch for
These examples use ASCII. Verify offset units and missing-match behaviour before indexing another string.