4

我有一个这样的字符串:

$data = 'id=1

username=foobar

comment=This is

a sample

comment';

我想删除\n第三个字段 ( comment=...) 中的 。

我有这个正则表达式可以满足我的目的,但不是很好:

preg_replace('/\bcomment=((.+)\n*)*$/', "comment=$2 ", $data);

我的问题是第二组中的每场比赛都会覆盖前一场比赛。因此,而不是这样:

'...
comment=This is a sample comment'

我最终得到了这个:

'...
comment= comment'

有没有办法将中间反向引用存储在正则表达式中?还是我必须匹配循环内的每个事件?

谢谢!

4

1 回答 1

4

这个:

<?php
$data = 'id=1

username=foobar

comment=This is

a sample

comment';

// If you are at PHP >= 5.3.0 (using preg_replace_callback)
$result = preg_replace_callback(
    '/\b(comment=)(.+)$/ms',
    function (array $matches) {
        return $matches[1] . preg_replace("/[\r\n]+/", " ", $matches[2]);
    },
    $data
);

// If you are at PHP < 5.3.0 (using preg_replace with e modifier)
$result = preg_replace(
    '/\b(comment=)(.+)$/mse',
    '"\1" . preg_replace("/[\r\n]+/", " ", "\2")',
    $data
);

var_dump($result);

会给

string(59) "id=1

username=foobar

comment=This is a sample comment"
于 2011-03-31T12:28:27.580 回答