使用正则表达式从缩进代码中删除额外的选项卡?

问题描述 投票:2回答:1

我的PHP代码是这样的:

$a = [
   "code" => "
        if(a == b) {
             doSomething();
        }
        ",
   // ...
];

现在,如果我在pre或textarea等空白保留标记中回显$a['code'],我得到:

        if(a == b) {
             doSomething();
        }

而我想:

if(a == b) {
     doSomething();
}

在实际输出中查看那些额外的标签/空格?如何从每行删除额外的标签时保留代码缩进?

我可以做像(\t){3}这样的正则表达式并用""替换它但是有更好的方法吗?

php regex
1个回答
0
投票

不幸的是,PHP没有内置的方法来实现这一点。默认情况下,我经常使用缩进做一些非常奇怪的事情。

在许多情况下,这是一个很好的标准,不要混合来自不同域的缩进,但它是强制执行的标准(交错时也很尴尬)。

例如在视图中:

<?php if(x): ?>
<html></html>
<?php endif; ?>

在复杂模板中实际上可能优于:

<?php if(x): ?>
    <html></html>
<?php endif; ?>

这是HTML缩进的HTML,PHP与PHP。在上面的例子中,您倾向于依赖语法突出显示来使事情更清晰。

如果你不介意表现,你可能会得到这样的东西:

function prune_outer_whitespace($str) {
    // IPTF who uses weird line endings.
    $lines = explode("\n", $str);
    // IPTF who uses multiline for single line.
    assert(count($lines) > 2);
    // IPTF who has an opening quote with content.
    assert($lines[0] === '');
    array_unshift($lines);
    // IPTF who didn't put the terminating quote on its own line.
    array_pop($lines);

    // IPTF who mixes indentation characters.
    assert(preg_match('/^([\t ]+)/', $lines[0], $matches));
    $start = $matches[1];
    $length = strlen($start);

    foreach($lines as &$line) {
        if($line === '') continue;
        // IPTF with insufficient indentation or non-empty empty lines.
        assert(strlen($line) > $length);
        // IPTF with insufficient indentation or mixed indentation.
        assert(!strncmp($start, $line, $length));
        $line = substr($line, $length);
    }

    return $lines;
}

未经测试且适用于:

$str = '
    if a
        b()
    else
        c()
';
$str = prune_outer_whitespace($str);

你可以用这个来打击性能,最终会出现奇怪的行为。您需要保留的约定以及对一个字符串类型或字符串内容有用的约定可能对另一个更不方便。

© www.soinside.com 2019 - 2024. All rights reserved.