PHP Regex: Select all except last occurrence

2019-08-02 02:39发布

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?

4条回答
闹够了就滚
2楼-- · 2019-08-02 02:56

You can use a lookahead:

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

See it working here: ideone

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-08-02 02:59
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

查看更多
迷人小祖宗
4楼-- · 2019-08-02 03:04

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);
?>
查看更多
聊天终结者
5楼-- · 2019-08-02 03:14

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.

查看更多
登录 后发表回答