PHP: Regex preg_replace_callback用于匹配PHP中的所有数字

时间:2022-09-08 13:26:31
preg_replace_callback( "/[0-9]*/", array( &$this, '_getPHPNumber' ), $code );

private function _getPHPNumber( $matches ) {
    return ( $this->_getHtmlCode( $matches[0], PHP::$Colors['number'] ) );
}

private function _getHtmlCode( $text, $color ) {
    $rows = array_filter( explode( "\n", $text ) );
    $count = count( $rows );
    $output = '';

    for ( $i = 0; $i < $count; $i++ ) {
        $n = ( $count > 1 ? ( $i != $count - 1 ? "\n" : "" ) : "" );
        $output .= "<span style=\"color:{$color};\">{$rows[$i]}</span>{$n}";

    }

    return ( $output );
}

The output of the above would look like this:

上述输出如下:

<span style="color:#FF0000;">152</span>

It works great, except if the number is a 0, it gets removed from output. The line causing the issue is $rows = array_filter( explode( "\n", $text ) ); in the _getHtmlCode. The exact cause is array_filter. If I remove it, my output gets completely broken, but the 0's appear. If I leave it, the 0's get removed.

它工作得很好,除非数字是0,否则它会从输出中删除。引起问题的行是$rows = array_filter(爆裂(“\n”,$text);_getHtmlCode。确切的原因是array_filter。如果我移除它,我的输出会被完全破坏,但是0会出现。如果我离开它,0就被移除。

Any ideas on how to fix this?

有什么办法解决这个问题吗?

1 个解决方案

#1


3  

The Man page for array_filter has your answer

array_filter的Man页面有您的答案

If no callback is supplied, all *entries of input equal to FALSE (see* converting to boolean) will be *removed.*

如果没有提供回调,则将删除所有等于FALSE的输入项(参见*转换为boolean)

And I believe 0 evaluates to FALSE.

我认为0的值为FALSE。

I can't test at the moment but I believe this will work

我现在无法测试,但我相信这行得通。

$rows = array_filter( explode( "\n", $text ), 'is_string' );

#1


3  

The Man page for array_filter has your answer

array_filter的Man页面有您的答案

If no callback is supplied, all *entries of input equal to FALSE (see* converting to boolean) will be *removed.*

如果没有提供回调,则将删除所有等于FALSE的输入项(参见*转换为boolean)

And I believe 0 evaluates to FALSE.

我认为0的值为FALSE。

I can't test at the moment but I believe this will work

我现在无法测试,但我相信这行得通。

$rows = array_filter( explode( "\n", $text ), 'is_string' );