Pruning a record pulled from MySQL

From the base we get the value of the field, which is, for example, 500 characters long. You need to cut up to 3-4 words and display only them. The question is how to implement it.


Answer 1

mysql solution:
let’s say we have a table table and a text field, then we can compose the following query:

select *,substring_index(text,' ',3) as text from table

Here the number 3 means the number of words.

php solution:
$text – a variable in which we store the text

$text = substr($text,0,strpos($text,' ',3));

Answer 2

preg_match_all('#[-]+\s#iu', $text, $res);
for ($i=0; $i<=3; $i++){
echo $res[0][$i].' ';
}

Something like this, we separate the text with spaces by words and then in a loop we output the first 4


Answer 3

In the vastness of the World Wide Web, I found such a function on this site:

CREATE FUNCTION `SPLIT_STRING`
(    str VARCHAR(2000),
     delim VARCHAR(12),
     pos INT )
RETURNS varchar(255) CHARSET utf8
COMMENT '   '
RETURN
     REPLACE(
          SUBSTRING(
               SUBSTRING_INDEX(str, delim, pos),
               CHAR_LENGTH(
                    SUBSTRING_INDEX(str, delim, pos - 1)
               ) + 1
          ),
          delim,
          ''
     )

I think it could be simplified by getting rid of the extra parameters posand delimto solve your problem for 3-4 words. Or use as-is.


Answer 4

well, or such a simple function can be used if we assume that the separation of words can be not one space, but several

  function cutstr($str,$cword){
        while($i<=strlen($str)){
         $char = substr($str,$i,1);
         if($char==' '){
            if(!$old){
                $n++;
                $old = 1;
            }
           } else $old=0;
         $cstr.=$char;
         if(intval($cword)==$n) break;
         $i++;
        }   
     return $cstr;
    }
    print cutstr(, );