PHP:正则表达式 preg_replace_callback 匹配 PHP 中的所有数字
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 );
}
上面的输出看起来像这样:
<span style="color:#FF0000;">152</span>
它工作得很好,除非数字是 0,它会从输出中删除。导致问题的行是 _getHtmlCode
中的 $rows = array_filter(explode( "\n", $text ) );
。确切的原因是array_filter
。如果我删除它,我的输出就会完全损坏,但会出现 0。如果我留下它,0 就会被删除。
关于如何解决这个问题有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
array_filter 的手册页有你的答案
我相信 0 评估为假。
我目前无法测试,但我相信这会起作用
The Man page for array_filter has your answer
And I believe 0 evaluates to FALSE.
I can't test at the moment but I believe this will work