Robert Hanson Robert Hanson - 6 months ago 83
PHP Question

PHP Split String After X Characters Into Separate Word


Possible Duplicate:

PHP: str_split without word-wrap




Let's say I have this string :

$string = "Lorem ipsum dolor sit amet";


and I have character limit on my database : 15 characters. by using str_split($string,15), I got this result :

Array
(
[0] => Lorem ipsum dol
[1] => or sit amet
)


this looks ugly to me... how to cut string to the closest word using PHP but the result is like this :

Array
(
[0] => Lorem ipsum
[1] => dolor sit amet
)

Answer

You can use wordwrap and explode

$string = "Lorem ipsum dolor sit amet";
$string = wordwrap($string, 15, ";;", true);
var_dump(explode(";;", $string));

Output

array
  0 => string 'Lorem ipsum' (length=11)
  1 => string 'dolor sit amet' (length=14)
Comments