The sentence case is one in english language in which the first character of the sentence is in capitals
and the rest ones are in lower case.
Lets see how can we convert the given string in sentence case in php.
$string = 'let say we need to change this string in sentence case.';
$sentences = preg_split('/([.?!]+)/', $string, -1,PREG_SPLIT_NO_EMPTY|REG_SPLIT_DELIM_CAPTURE);
$newString = '';
foreach ($sentences as $key => $sentence) {
$newString .= ($key & 1) == 0 ? ucfirst(strtolower(trim($sentence))) : $sentence.' ';
}
echo trim($newString);
In the above code we have first set a variable $string with the string having the first character in lower case.
Now, we need to make in uppercase for the proper sentence case.
Then, using the preg_split() php function which uses the regular expression to split the given string we will pass our string the regular expression and passed the result in $sentences.
Afterwards in the foreach loop we have extracted the first character from the $sentences array
and in the ternary condition the first element of the $sentences array is set to uppercase with the ucfirst() string function and then printed the sentence.
In this way we can convert the given string in sentence case using php.
0 Comment(s)