开发者

PHP: Regex preg_replace_callback to match all numbers in PHP

开发者 https://www.devze.com 2023-03-17 09:44 出处:网络
preg_replace_callback( \"/[0-9]*/\", array( &$this, \'_getPHPNumber\' ), $code ); private function _getPHPNumber( $matches ) {
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.

Any ideas on how to fix this?


The Man page for array_filter has your answer

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

And I believe 0 evaluates to FALSE.

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

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

精彩评论

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

关注公众号