I'm trying to replace all 's sans that final one with
\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('/ (.+?) /',' \t$1 ',$var);
It currently spits this out:
This
that
then
thar
these
them
Need to indent every line less the first and last line using regex, how can I accomplish this?
After fixing a quotes issue, your output is actually like this:
This
that
then
thar
these
them
Use a positive lookahead to stop that trailing 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.
echo preg_replace('/
(.+?)(?=
)/', "
\t$1", $input);
// newline-^ ^-text ^-lookahead ^- replacement
preg_replace('/
(.+?)(?=
)/',"
\t$1",$var);
Modified the second to be the lookahead
(?= )
, otherwise you'd run into issues with regex not recognizing overlapping matches.
You can use a lookahead:
$var = preg_replace('/
(?=.*?
)/', "
\t", $var);
See it working here: ideone
Let the downwoting begin, but why use regex for this?
<?php
$e = explode("
",$oldstr);
$str = $e[count($e) - 1];
unset($e[count($e) - 1]);
$str = implode("
\t",$e)."
".$str;
echo $str;
?>
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:
<?php
$count = substr_count($oldstr,"
") - 1;
$newstr = str_replace("
","
\t",$oldstr,&$count);
?>