2

Possible Duplicate:
Replace only first match using preg_replace

I have a string as follows:

a     quick brown      fox jumps    over a lazy dog

and I want the result to be

a
quick brown      fox jumps     over a lazy dog

Want to replace only the first occurrence of multiple(more than 1) whitespace with a newline, but leave the other multiple whitespaces after that untouched.

How can I do that with preg_replace?

Thanks

Community
  • 1
  • 1
WebNovice
  • 2,230
  • 3
  • 24
  • 40

3 Answers3

3
echo preg_replace('/\s{2,}/', "\n", $string, 1);

From the PHP documentation, the fourth argument to preg_replace is an optional limit, limiting the number of times the pattern should be replaced.

Michael Robinson
  • 29,278
  • 12
  • 104
  • 130
3

Use the optional fourth parameter, setting the limit of replacements made for the pattern:

$str = preg_replace( "/\s{2,}/", PHP_EOL, $str, 1 );

Demonstration: http://codepad.org/Kocnyryj

Sampson
  • 265,109
  • 74
  • 539
  • 565
2

Use preg_replace()'s $limit to only replace one occurrence.

$string = preg_replace("/\s\s+/", "\n", $string, 1); // \s\s+ to replace 2 or more
// Where  preg_replace($pattern, $replacement, $subject, $limit);

$limit The max possible replacements for each pattern in each subject string. Defaults to -1 (no limit).

0b10011
  • 18,397
  • 4
  • 65
  • 86
  • 1
    @AlexLunix, actually, it *wasn't* correct (either were the other answers), but now it is :) (Previously, I had `\s+` which would match `1 or more`, but the OP was requesting `more than 1` *or* `2 or more`.) – 0b10011 May 10 '12 at 20:36
  • thanks, this also works. Wish I could choose both answers. – WebNovice May 10 '12 at 20:44