tags:

views:

35

answers:

3

How can i replace {number}) with \n{number})

Say i have something like this

1) test string testing new string. 2) that is also a new string no new line. 3) here also no new lines.

The output should be something like this

1) test string testing new string.

2) that is also a new string no new line.

3) here also no new lines.

How can i do that with a regex?

+7  A: 
$outputstring = preg_replace('/([0-9]+)\)/', "\n$1)", $inputstring);

Matches any set of digits followed by a literal ), replaces with a newline followed by those digits followed by a ).

If you want there to actually be a blank line in between like in your example output, you'd actually want to insert two newlines (since you need a newline to end the line with text, and then another to add the blank line). Just make it \n\n instead of \n in the second argument if such is the case.

Also note that this will add a newline at the beginning of the string if it starts with a numbered point, so you might want to trim the string afterwards if you don't want the leading newline.

Amber
Thanks with \n\n it works perfect, thanks again and have a nice day
streetparade
I would think about using `PHP_EOL` instead of \n though :)
Svish
+1  A: 

User preg_replace Function

$str = "1) test string testing new string. 2) that is also a new string no new line. 3) here also no new lines.";

print preg_replace("/(\d+\))/","\n$1" , $str);
pavun_cool
+2  A: 
$result = preg_replace('/(?<!\A|\n\n)(?=[0-9]+\))/m', '\n\n', $subject);

will do the same thing as Dav's solution but will also leave numbers at the start of the string alone (in this case 1)). It will also leave numbers alone if there already are two linebreaks before them.

Tim Pietzcker