Lets say I have the following sentence:
A quick brown fox jumped over a lazy dog.
However I have a limit, that only 25 characters can be allowed in that sentence. This might leave me with something like:
A quick brown fox jum
However, that sentence doesn't make any grammatical sense, so I would prefer to find the last word which we can allow while staying in the 25 char limit. This will give us something like:
A quick brown fox
Which will be less than the 25 char limit, however it makes more grammatical sense. I.e the word isn't broken up, we have the maximum number of comprehensible words while staying in the limit.
How can I code a function which will take a string, and a char limit such as 25, and if the string exceeds the limit, returns the string with the max number of words possible?
Answer: Use the PHP strpos() Function You can use the PHP strpos() function to check whether a string contains a specific word or not. The strpos() function returns the position of the first occurrence of a substring in a string. If the substring is not found it returns false .
Use the Contains() method to check if a string contains a word or not.
Answer: Use the PHP str_replace() function You can use the PHP str_replace() function to replace all the occurrences of a word within a string.
A string is a collection of given characters and a substring is a string present in a given string. In this article, we are going to check if the given string contains a substring by using the PHP strpos() function. Syntax: strpos($original_string,$sub_string);
It's easy enough using regex:
function first_few_words($text, $limit) {
// grab one extra letter - it might be a space
$text = substr($text, 0, $limit + 1);
// take off non-word characters + part of word at end
$text = preg_replace('/[^a-z0-9_\-]+[a-z0-9_\-]*\z/i', '', $text);
return $text;
}
echo first_few_words("The quick brown fox jumps over the lazy dog", 25);
Some extra features of this implementation:
Edit: changed regex so that only letters, digits, '_' and '-' are considered word characters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With