How to check what a string ends with
Short answer
str_ends_with() returns true if the string ends with the substring:
<?php
var_dump(str_ends_with('report.pdf', '.pdf'));Output:
bool(true)Ignoring case
Convert the string to lowercase:
<?php
var_dump(str_ends_with(strtolower('PHOTO.JPG'), '.jpg'));Output:
bool(true)Several options
Go through the allowed endings:
<?php
$file = 'photo.png';
$isImage = false;
foreach (['.jpg', '.png', '.webp'] as $extension) {
if (str_ends_with($file, $extension)) {
$isImage = true;
}
}
var_dump($isImage);Output:
bool(true)Functions used in this recipe
- str_ends_with — Checks whether a string ends with a given substring.
- str_starts_with — Checks whether a string starts with a given substring.
- pathinfo — Splits a path into parts: the folder, the name and the extension.