Reputation: 97
I have strings like this:
123 qwerty 6 foo bar 55 bar
I need to make it like this
123 qwerty
6 foo bar
55 bar
How to make it?
UPD: I tried make it
$subject = "123 qwerty 6 foo 55 bar";
$pattern = '/[^0-9]/';
preg_match($pattern, substr($subject,3), $matches, PREG_OFFSET_CAPTURE);
echo "<pre>";
print_r($matches);
But it is no working for me.
Upvotes: 0
Views: 742
Reputation: 11552
Try this:
$subject = '123 qwerty 6 foo 55 bar';
$pattern = '/ (?=[\d]+)/';
$replacement = "\n";
$result = preg_replace( $pattern, $replacement, $subject );
print_r( $result );
Produces:
123 qwerty
6 foo
55 bar
PHP Demo: http://codepad.org/MNLgaySd
The key is in the regular expression's "positive lookahead", (?=...)
Regex Demo: http://rubular.com/r/i4CdoEL9f4
Upvotes: 0
Reputation: 5868
Like this:
$lineending= "\n";
$parts= explode(' ',$string);
$result= "";
for($i=0; $i<count($parts);){
$result .= $parts[$i];
while(!is_numeric($parts[$i]) && $i<count($parts)){
$result .= $parts[$i];
$i+= 1;
}
$result .= $lineending;
}
;-)
Upvotes: 2
Reputation: 2900
you can use this:
$text = '123 qwerty 6 foo 55 bar baz';
$result = preg_replace('/([0-9]+[^0-9]+)/i', '$1\n', $text);
This looks for at least one number followed by at least one character which is NOT a number and adds a linebreak.
Read more abot:
Upvotes: 3