开发者

PHP Regex: Select all except last occurrence

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:

$var = preg_replace('/\n(?=.*?\n)/', "\n\t", $var);

See it working here: ideone


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 \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.

echo preg_replace('/\n(.+?)(?=\n)/', "\n\t$1", $input);
//          newline-^  ^-text ^-lookahead ^- replacement

Live demo.


preg_replace('/\n(.+?)(?=\n)/',"\n\t$1",$var);

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?

<?php
$e = explode("\n",$oldstr);
$str = $e[count($e) - 1]; 
unset($e[count($e) - 1]);
$str = implode("\n\t",$e)."\n".$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,"\n") - 1;
$newstr = str_replace("\n","\n\t",$oldstr,&$count);
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜