Check if String Ends With a Slash in PHP

This tutorial will discuss about a unique way to check if string ends with a slash in php.

To check if string ends with a slash in PHP, we can use the substr() function.

It accepts a string as the first parameter and an offset value as the second parameter. As we want to fetch the last character of the string so we will pass the offset as -1 i.e. substr($str, -1). In that case the substr() function will return the last character of the string.

Then we can compare it with this slash, but before that we need to make sure that the string has at least one character. For that we will fetch the length of the string using the strlen() function and check if it is more than 0.

We have created a separate function to check if the string ends with the slash i.e.

function endsWithSlash($str)
{
    // Check if size of string is more than 0
    // Fetch last character and check if it is a slash
    return  strlen($str) > 0 &&
            substr($str, -1) === "/";
}

It accepts a string as an argument and returns true if the string ends with a slash.

Let’s see the complete example,

<?php
/**
 * Checks if a string ends with a slash ("/") using substr().
 *
 * @param string $str The string to check.
 * @return bool True if the string ends with a slash, false otherwise.
 */
function endsWithSlash($str)
{
    // Check if size of string is more than 0
    // Fetch last character and check if it is a slash
    return  strlen($str) > 0 &&
            substr($str, -1) === "/";
}

$strValue = "https://thispointer.com/";

// Check if string ends with a slash
if (endsWithSlash($strValue)) {
    echo "The string ends with a slash.";
} else {
    echo "The string does not end with a slash.";
}
?>

Output

The string ends with a slash.

Summary

We learn about a way to check a string ends with a slash in PHP.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top