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...
- How To Use Php Conditional Statement Example
- How to Check if String Contains Regex in PHP?
- PHP Array_column() Function Example
- PHP Generate List of Random Numbers Between 0 and 100 Example
- How to User Login with Facebook in PHP?
- How to Explode Every Character into Array Using PHP Example?
- PHP Form Validation Tutorial
- PHP Convert XML to JSON Example