views:

60

answers:

3

Hi. 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

+1  A: 

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

Breezer
uhm yeah. good idea. Only problems is that im a beginner with regular expression, and i don't know how to say [all except space]. Because i need to check all type of string (every chars) without the space, the delimiter :)
markzzz
markzzz: You can use `explode` for that. If you want all except space use `[\S]`. However I question use of regexes for so simple a problem ... seems like it makes things unnecessarily complicated IMHO. YMMV.
Billy ONeal
A: 
$result = array();
$source = // assign source here
for($idx = 0; $idx < count($source); $idx += 5) {
    $result = substr($source, $idx, 5);
}
Billy ONeal
+3  A: 

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.

Vincent Savard
yeah! this works!!! but i need to add the "#" characters when i split it :) How can i do this? Yeah i know, i need to learn the REGEX :)
markzzz
try '$1#' instead of '$1 ' for a hash instead of space
esryl
esryl is entirely right. I edited my post to match what you wanted (could have sworn you wanted a space though :-p )
Vincent Savard
thanks to both :)
markzzz
I edited again, I forgot that it should match the end of the string as well.
Vincent Savard
Thanks. Now there's another problem : i've add this regex into my main preg_replace function, which i also evalutate some bbcode tag. So, if now i have "aaa bbbb[b]hi[/b] it will fails, because in the next step it doesn't recognize the [b][/b] bbcode tag. Is it better open a new topic for this problem?
markzzz