Home > Net >  Searching a string that begins with "Mon" and storing it in element 0 in an array
Searching a string that begins with "Mon" and storing it in element 0 in an array

Time:07-10

<?php
 $towns = 'Monday Tuesday Sunday Friday';

 $towns1 = strtolower($towns);

$words = explode(" " , $towns1);

echo \n;
echo $words

This is what I have so far I have exploded the string into arrays but how do I search or what is the best approach to find words that begins with "Mon" and storing it in a new array ? I'm new to PHP here

CodePudding user response:

<?php
    $towns = 'Monday Tuesday Sunday Friday';
    $towns1 = strtolower($towns);
    $input = explode(" ", $towns1);
    //print_r($input);
    $result = preg_grep("/^mon/i", $input);
    print_r($result);
?>

CodePudding user response:

Put this in your code:

foreach($words as $word){
    switch(true){
        case str_starts_with($word, 'Monday'):
            ## Code to be executed
            break;
        case str_starts_with($word, 'Tuesday'):
            ## Code to be executed
            break;
        case str_starts_with($word, 'Sunday'):
            ## Code to be executed
            break;
        case str_starts_with($word, 'Friday'):
            ## Code to be executed
            break;
    }
}
  •  Tags:  
  • php
  • Related