Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP string/word processing question

Tags:

string

php

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?

like image 637
Ali Avatar asked Aug 26 '09 01:08

Ali


People also ask

How do I check if a string contains a specific word in PHP?

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 .

How do I check if a string contains a specific word?

Use the Contains() method to check if a string contains a word or not.

How do I remove a word from a string in PHP?

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.

How do you check if a string contains another string in PHP?

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);


1 Answers

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:

  • Splits words at linebreaks and tabs also.
  • Saves an extra word which ends at character 25.

Edit: changed regex so that only letters, digits, '_' and '-' are considered word characters.

like image 103
too much php Avatar answered Sep 21 '22 22:09

too much php