Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pull first X words (not just characters) from mySQL

Tags:

php

mysql

I'd like to be able to pull the first X words from a database field for use in a preview. Basically if a field 's content was

 "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris malesuada."

I would like to echo

 "Lorem ipsum dolor sit amet... see more"

What's the best way to do this?

The only thing I know to do is pull the whole field in a query then do something like

$foo = [query_results];
$bar = explode(' ', $foo);
for($x=0, $x<6, $x++){
     echo $bar[$x];
};
echo "... see more"

Is there a better approach to this?

like image 999
Chris Sobolewski Avatar asked Feb 20 '10 04:02

Chris Sobolewski


People also ask

How do I get the first word in MySQL?

To select first word in MySQL query, you can use SUBSTRING_INDEX().

How do I get the first letter of each word in MySQL?

To fetch the first alphabet from the strings, use LEFT(). This method allows you to return characters from the left of the string.

How do I separate words in MySQL?

In MySQL, we use SUBSTRING_INDEX() to split the string. It usually consists of three arguments i.e., string, delimiter, and position. The string value will be split based on the position.

How do I find a specific word in MySQL?

LOCATE() function MySQL LOCATE() returns the position of the first occurrence of a string within a string. Both of these strings are passed as arguments. An optional argument may be used to specify from which position of the string (i.e. string to be searched) searching will start.


1 Answers

You definitely want to use SUBSTRING_INDEX which will return some number of characters until a specified count is achieved based on the occurrence of a delimiter. In your case the call would look like this:

 SELECT SUBSTRING_INDEX(text_field, ' ', 6) FROM ...

In particular, this will return up to six words where we define a word as a set of characters that are not spaces delimited by spaces.

Note: this will return punctuation attached to the last word, which may or may not be desired. It'd be simple enough to replace any punctuation characters at the tail of the string in PHP, but if you want to stay completely within SQL I think you can use TRIM. The syntax for that would be something like:

SELECT TRIM(TRAILING ',' FROM SUBSTRING_INDEX(text_field, ' ', 6)) FROM ...

There may be a better option for removing the trailing punctuation -- but perhaps that's another question (I'm still looking for a better solution than TRIM).

like image 151
Mark Elliot Avatar answered Oct 22 '22 07:10

Mark Elliot