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

2 Answers

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

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

echo $result;
 
     
    
            
     
/*
run:
                 
true
          
*/

 



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

 



answered Feb 27, 2021 by avibootz

Related questions

1 answer 189 views
1 answer 179 views
1 answer 203 views
1 answer 223 views
...