user2854563
user2854563

Reputation: 268

Smart Word Wrap?

I'm using PHP having the following string:

$message = 'hello, DavidPalmerUgroImmIErogandTagroChechiken ho are you?';

I want to split the word if string's ANY word is long then 15 characters. How can I do this?

I searched and found answers of splitting WHOLE string but not just splitting a WORD if that particular word is more then 15 characters long. Please help!

Upvotes: 0

Views: 350

Answers (3)

Ram Sharma
Ram Sharma

Reputation: 8809

you can try something like this as well.

$newMessage = preg_replace('/(\S{15})(?=\S)/', '$1 ', $message);

Upvotes: 3

Joe
Joe

Reputation: 15802

This is a relatively basic solution, and there are things you can improve on (better word detection, putting 14-letters then a hyphen for interrupted words, etc), but this should give you a good starting point.

You could also do this with regex (/[^\s]{15,}/ as your basic starting point) if you're comfortable with that - just horses for courses :-)


Split the string into words:

$words = explode(' ', $message); // could also split on other punctuation or detect words more reliably here

Iterate the words to see if any are >15 letters

foreach ($words AS $key => $word) {
    if (strlen($word) > 15) {
        // ...
    }
}

then when you find one, cut it up into smaller parts

$words[$key] = implode(' ', str_split($word, 15));

and lastly, join it all back up.

$words = implode(' ', $words);

Complete code:

$words = explode(' ', $message); // could also split on other punctuation or detect words more reliably here

foreach ($words AS $key => $word) {
    if (strlen($word) > 15) {
        $words[$key] = implode(' ', str_split($word, 15));
    }
}

$words = implode(' ', $words);

Upvotes: 3

user4066167
user4066167

Reputation:

Just get the size of your word with

$length = strlen($yourword);

then if thats bigger than 15, you can use chunksplit to separate it in smaller chunks.

Upvotes: 0

Related Questions