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

3 Answers

0 votes
$s = "php python c c++ java";

$match = 'java';
  
if (substr_compare($s, $match, strlen($s) - strlen($match), strlen($match)) === 0) {
    echo "yes";
}
else {
    echo "no";
}

    
   
           
    
/*
run:
                
yes
         
*/

 



answered Nov 20, 2019 by avibootz
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, $s_len - $m_len, $m_len) === 0;
}

$s = "php python c c++ java";

if (string_ends_with($s, "java")) {
    echo "yes";
}
else {
    echo "no";
}

    
   
           
    
/*
run:
                
yes
         
*/

 

 



answered Nov 20, 2019 by avibootz
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";

if (string_ends_with($s, "java")) {
    echo "yes";
}
else {
    echo "no";
}

    
   
           
    
/*
run:
                
yes
         
*/

 



answered Nov 20, 2019 by avibootz

Related questions

2 answers 179 views
1 answer 182 views
1 answer 162 views
1 answer 140 views
3 answers 177 views
1 answer 169 views
...