How to check if a string ends with another string in PHP

2 Answers

0 votes
function string_ends_with($s, $match) {
    $s_len = strlen($s);
    $m_len = strlen($match);
    if ($m_len > $s_len) {
        return false;
    }
     
    return substr_compare($s, $match, -$m_len) === 0;
}

$s = "php python c c++ java";
 
$result = string_ends_with($s, "java") ? "true" : "false";

echo $result;
 
     
    
            
     
/*
run:
                 
true
          
*/

 



answered Feb 27, 2021 by avibootz
0 votes
$s = "php python c c++ java";
$word = " java";  
  
$result = strpos($s, " java") === strlen($s) - strlen($word) ? "true" : "false";
 
echo $result;

      
     
             
      
/*
run:
                  
true
           
*/

 



answered Feb 27, 2021 by avibootz

Related questions

...