I'm trying to replace all \n
's sans that final one with \n\t
in order to nicely indent for a recursive function.
This
that
then
thar
these
them
should become:
This
that
then
thar
these
them
This is what I have: preg_replace('/\n(.+?)\n/','\n\t$1\n',$var);
It currently spits this out:
This
that
then
thar
these
them
Quick Overview:
Need to indent every line less the first and last line using regex, how can I accomplish this?
You can use a lookahead:
See it working here: ideone
Modified the second
\n
to be the lookahead(?=\n)
, otherwise you'd run into issues with regex not recognizing overlapping matches.http://ideone.com/1JHGY
Let the downwoting begin, but why use regex for this?
Actually, str_replace has a "count" parameter, but I just can't seem to get it to work with php 5.3.0 (found a bug report). This should work:
After fixing a quotes issue, your output is actually like this:
Use a positive lookahead to stop that trailing
\n
from getting eaten by the search regex. Your "cursor" was already set beyond it so only every other line was being rewritten; your match "zones" overlapped.Live demo.