PHP str_ends_with
Check the end of a filename when listing receipts saved as PDFs.
A simple example
str_ends_with
- Start with "abc" and "bc"
- Do this Compare the ending
- Result Yes
<?php
$value = "abc";
$other = "bc";
echo ((str_ends_with($value, $other)) ? "yes" : "no"), PHP_EOL;
yes
Syntax
str_ends_with($label, ".pdf")
Run these examples in PHP
Save one example at a time as lesson.php. Use PHP 8.2 or later.
php lesson.phpFind filenames with a receipt extension
A document picker displays receipt files alongside unrelated attachments. Filter by the expected ending so the clerk sees the right filenames before opening any of the files.
<?php
$label = "receipt.pdf";
echo ((str_ends_with($label, ".pdf")) ? "yes" : "no"), PHP_EOL;
yes
The final four characters match .pdf. A filename such as receipt.pdf.old would fail the check.
Find a class roster
A folder contains active exports alongside files with similar names and additional suffixes. Inspect the final filename or extension carefully before placing an entry in the report.
<?php
$value = "class.csv";
$other = ".csv";
echo ((str_ends_with($value, $other)) ? "yes" : "no"), PHP_EOL;
yes
The final characters match the requested extension.
Exclude a backup export
A registry keeps an earlier export by adding an extra extension to its filename. Test the filename's final suffix before treating the file as part of today's import.
<?php
$value = "class.csv.old";
$other = ".csv";
echo ((str_ends_with($value, $other)) ? "yes" : "no"), PHP_EOL;
no
The final extension is .old.
What to watch for
A filename suffix describes a naming convention. It cannot verify the contents of a file.