What's the Most Efficient Test of Whether a PHP String Ends with Another String

What's the most efficient test of whether a PHP string ends with another string?

What Assaf said is correct. There is a built in function in PHP to do exactly that.

substr_compare($str, $test, strlen($str)-strlen($test), strlen($test)) === 0;

If $test is longer than $str PHP will give a warning, so you need to check for that first.

function endswith($string, $test) {
$strlen = strlen($string);
$testlen = strlen($test);
if ($testlen > $strlen) return false;
return substr_compare($string, $test, $strlen - $testlen, $testlen) === 0;
}

matching a word to end of string with strpos

You can make use of strrpos function for this:

$str = "Oh, hi O";
$key = "O";

if(strlen($str) - strlen($key) == strrpos($str,$key))
print "$str ends in $key"; // prints Oh, hi O ends in O

or a regex based solution as:

if(preg_match("#$key$#",$str)) {
print "$str ends in $key"; // prints Oh, hi O ends in O
}

startsWith() and endsWith() functions in PHP

PHP 8.0 and higher

Since PHP 8.0 you can use the

str_starts_with
Manual
and

str_ends_with Manual

Example

echo str_starts_with($str, '|');

PHP before 8.0

function startsWith( $haystack, $needle ) {
$length = strlen( $needle );
return substr( $haystack, 0, $length ) === $needle;
}
function endsWith( $haystack, $needle ) {
$length = strlen( $needle );
if( !$length ) {
return true;
}
return substr( $haystack, -$length ) === $needle;
}

Check if a String Ends with a Number in PHP

$test="abc123";
//$test="abc123n";
$r = preg_match_all("/.*?(\d+)$/", $test, $matches);
//echo $r;
//print_r($matches);
if($r>0) {
echo $matches[count($matches)-1][0];
}

the regex is explained as follows:

.*? - this will take up all the characters in the string from the start up until a match for the subsequent part is also found.

(\d+)$ - this is one or more digits up until the end of the string, grouped.

without the ? in the first part, only the last digit will be matched in the second part because all digits before it would be taken up by the .*

If string ends with these characters, then

You can use substr, rtrim and strpos for this, like this:

$result = strpos("!?.", substr(rtrim($text), -1)) !== false;

This will set $result to true or false as you have indicated.

how to know if a $string ends with ','?

There are a few options:

if (substr($string, -1) == ',') {

Or (slightly less readable):

if ($string[strlen($string) - 1] == ',') {

Or (even less readable):

if (strrpos($string, ',') == strlen($string) - 1) {

Or (even worse yet):

if (preg_match('/,$/', $string)) {

Or (wow this is bad):

if (end(explode(',', $string)) == '') {

The take away, is just use substr($string, -1) and be done with it. But there are many other alternatives out there...

How to check if a string starts with a specified string?

PHP 8 or newer:

Use the str_starts_with function:

str_starts_with('http://www.google.com', 'http')

PHP 7 or older:

Use the substr function to return a part of a string.

substr( $string_n, 0, 4 ) === "http"

If you're trying to make sure it's not another protocol. I'd use http:// instead, since https would also match, and other things such as http-protocol.com.

substr( $string_n, 0, 7 ) === "http://"

And in general:

substr($string, 0, strlen($query)) === $query

What is the fastest way to find the occurrence of a string in another string?

strpos seems to be in the lead, I've tested it with finding some strings in 'The quick brown fox jumps over the lazy dog':

  • strstr used 0.48487210273743 seconds for 1000000 iterations finding 'quick'
  • strpos used 0.40836095809937 seconds for 1000000 iterations finding 'quick'
  • strstr used 0.45261287689209 seconds for 1000000 iterations finding 'dog'
  • strpos used 0.39890813827515 seconds for 1000000 iterations finding 'dog'
<?php

$haystack = 'The quick brown fox jumps over the lazy dog';

$needle = 'quick';

$iter = 1000000;

$start = microtime(true);
for ($i = 0; $i < $iter; $i++) {
strstr($haystack, $needle);
}
$duration = microtime(true) - $start;
echo "<br/>strstr used $duration microseconds for $iter iterations finding 'quick' in 'The quick brown fox jumps over the lazy dog'";

$start = microtime(true);
for ($i = 0; $i < $iter; $i++) {
strpos($haystack, $needle);
}
$duration = microtime(true) - $start;
echo "<br/>strpos used $duration microseconds for $iter iterations finding 'quick' in 'The quick brown fox jumps over the lazy dog'";

$needle = 'dog';

$start = microtime(true);
for ($i = 0; $i < $iter; $i++) {
strstr($haystack, $needle);
}
$duration = microtime(true) - $start;
echo "<br/>strstr used $duration microseconds for $iter iterations finding 'dog' in 'The quick brown fox jumps over the lazy dog'";

$start = microtime(true);
for ($i = 0; $i < $iter; $i++) {
strpos($haystack, $needle);
}
$duration = microtime(true) - $start;
echo "<br/>strpos used $duration microseconds for $iter iterations finding 'dog' in 'The quick brown fox jumps over the lazy dog'";

?>

How do I check if a string contains a specific word?

Now with PHP 8 you can do this using str_contains:

if (str_contains('How are you', 'are')) { 
echo 'true';
}

RFC

Before PHP 8

You can use the strpos() function which is used to find the occurrence of one string inside another one:

$haystack = 'How are you?';
$needle = 'are';

if (strpos($haystack, $needle) !== false) {
echo 'true';
}

Note that the use of !== false is deliberate (neither != false nor === true will return the desired result); strpos() returns either the offset at which the needle string begins in the haystack string, or the boolean false if the needle isn't found. Since 0 is a valid offset and 0 is "falsey", we can't use simpler constructs like !strpos($a, 'are').



Related Topics



Leave a reply



Submit