I am trying to get first two word from a sentence using php
$inp_val= "this is our country";
output will be : this is
// this input value has different string as Like: this, this is our, this name is mine
// i need to get only first two word or if anyone wrote only one word then i got same word but if any one wrote two or more word then it will collect only first two word..
I am trying with below code but it won't work properly..
$words = explode(' ', $inp_val);
$shop_name = "";
if (str_word_count($words) == 1) {
$shop_name .= mb_substr($words[0], 0, 1);
} else {
for ($i = 0; $i < 2; $i ) {
$w = $words[$i];
$shop_name .= mb_substr($w, 0, 1);
}
}
CodePudding user response:
After exploding the input value by space (as you have done), you can use array_slice
to extract the 2 first elements, then use the implode
to concat the 2 elements as a string.
$inp_val = "this is our country";
$shop_name = implode(" ", array_slice(explode(' ', $inp_val), 0, 2));
echo $shop_name;
//OUTPUT: this is
This method that uses array_slice
work well for one or more words