How to Check If String Ends With Specific String in PHP?

Nov 10, 2022

.

Admin

How to Check If String Ends With Specific String in PHP?

Hi Dev,

This simple article demonstrates of How to check if string ends with specific string in PHP. This tutorial will give you simple example of Checks if a string ends with a given sub-string. this example will help you use the ends-with functions in PHP. you will learn String check if Ends With With Code Examples. Follow bellow tutorial step of Function to check the string is ends with given sub-string or not.

Example 1:


index.php

<?php

$string = "hello world";

$substring = "world";

$length = strlen($substring);

if ( substr_compare($string, $substring, -$length) === 0 ) {

echo "\"{$string}\" ends with \"{$substring}\".";

} else {

echo "\"{$string}\" does not end with \"{$substring}\".";

}

?>

Output:

"hello world" ends with "world".

Example 2:

index.php

<?php

// Function to check the string is ends

// with given substring or not

function endsWith($string, $endString)

{

$len = strlen($endString);

if ($len == 0) {

return true;

}

return (substr($string, -$len) === $endString);

}

// Driver code

if(endsWith("nices","es"))

echo "True";

else

echo "False";

?>

Output:

True

I hope it could help you...

#PHP