0

Lets say I need to get a string from MySQL database smaller than 150 characters BUT I do not want to cut the last word, instead I need it until the last space and less than 150 characters. For example:

I want:

Derrick Rose and the Chicago Bulls.

I don't want:

Derrick Rose and the Chica.

Is there a way to do this in MySQL, PHP or a combination of both?

boompow
  • 131
  • 1
  • 12

2 Answers2

2

You can do this with the built-in string functions:

  • reverse the first 150 characters of the string
  • find the first space in the reversed string
  • use this information to get the right string

The SQL looks something like this:

select left(left(str, 150), 150 - locate(' ', reverse(left(str, 150))))
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

Write a loop in PHP that starts at position 150, and works back until it encounters either a space character, or the start of the string.

If it encounters a space character, take all characters from the start of the string to the position you just found. Otherwise, use the first 150 characters (edge case that there are no space characters in the first 150).

Eric J.
  • 147,927
  • 63
  • 340
  • 553