How to Pregreplace {number}) with \n{number})
How can i replace {number})
with \n{number})
Say i have something lik开发者_StackOverflow中文版e 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?
$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.
$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.
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);
精彩评论