Regex in PHP

Bes

Bes

Soldato
Joined
18 Oct 2002
Posts
7,318
Location
Melbourne
Hi,

I have a tricky RegEx I am trying to get to the bottom of...

I want to look at the value of every 12th character, then backtrack and replace the LAST space I find with a \n. (So it backtracks from the 12th char back to the previous space and subs that) For example...

"The quick brown fox jumps over the lazy brown dog"

Becomes

"The quick\nbrown fox\njumps over\nthe lazy\nbrown dog"

The closest I can get is to do this:

if (strlen ($annotate)>11)
{
$annotate=preg_replace("/(.*)?( )/","$0\n",$annotate);
}

But this only does the last space of each string fed into it. I know using the if statement is the wrong approach, but I'm very stuck here.

Any help greatly appreciated

Thanks
 
Last edited:
PHP:
<?php
function splitBySpaces($str,$maxChars = 12){
    $str = str_split($str,$maxChars);
    $out = '';
    foreach ($str as $s){
        $strrpos = strrpos($s,' ');
        if ($strrpos){
            $out .= substr_replace(
                $s,
                "\n",
                strrpos($s,' '),
               1 
            );
        } else {
            $out .= $s;
        }
    }
    return $out;
}
$str = 'The quick brown fox jumps over the lazy brown dog';
echo splitBySpaces($str);
?>
Hi,

I spent an hour or 2 looking over your code... if I give it the string "Bes OCUK" it still linebreaks but I can't figure out why? :( Any ideas why? as I would expect it to all be on one line.

Thanks
 
Back
Top Bottom