markzzz
markzzz

Reputation: 47995

PHP - split a string if its contain words longer more than 5 chars

As topic said, I need a recursive function that split a string if its contain words longer more than (for example) 5 chars.

Example :

if i have the string "aaaaa aaa a aaaa aaaaa" its ok;

if i have the string "aaaaa bbbbbb aa aaaaa" I need to split 1 time (and, for example, add the char # before the first bbbbb and the last b). So the result will be "aaaaa bbbbb#b aa aaaaa"

if i have the string "aaaaa bbbbbbbbbbbbbbbb aa aaaaa" as before; notice that the bold one this time have 16 chars, so i need to split 3 time this time :)

Is there any php function already implemented or i need to make it? Cheers

Upvotes: 0

Views: 679

Answers (3)

Vincent Savard
Vincent Savard

Reputation: 35927

Using preg_replace :

echo preg_replace("`(\S{5})(?!\s|$)`", '$1#', "aaaaa bbbbbbbbbbbbbbbb aa aaaaa")
// aaaaa bbbbb#bbbbb#bbbbb#b aa aaaaa

Notice I replace every set of 5 characters not followed by a space by the set of 5 characters + #. You can obviously replace the # with anything else.

Upvotes: 3

Billy ONeal
Billy ONeal

Reputation: 106589

$result = array();
$source = // assign source here
for($idx = 0; $idx < count($source); $idx += 5) {
    $result = substr($source, $idx, 5);
}

Upvotes: 0

Breezer
Breezer

Reputation: 10490

one way would be using split() and use a regex such as this one

[a-zA-Z]{5}

so

split('[a-zA-Z]{5}',$string);

edit: just noticed the function is DEPRECATED so use preg_split instead

Upvotes: 1

Related Questions