[英]How to replace 0 with an empty string in PHP
I'm building a report in PHP, and am really new to this language.我正在 PHP 中构建报告,并且对这种语言真的很陌生。
I read the documentation on preg_replace, but it's not working exactly as I expect.我阅读了有关 preg_replace 的文档,但它并没有像我预期的那样工作。
Here's my code:这是我的代码:
$pattern = 0;
$replacement = ' ';
$report_output.= '
<td>'.preg_replace($pattern, $replacement, round($row[$win_count])).'</td>
';
Instead of replacing a result of 0 with an empty string, it replaces all results with an empty string.它不是用空字符串替换 0 的结果,而是用空字符串替换所有结果。 The round works great like this:
这一轮的效果很好,就像这样:
<td>'.round($row[$win_count]).'</td>
It's just when I put the preg_replace around it, it says 'phooey, I shall replace everything'.就在我把 preg_replace 放在它周围时,它说“糟糕,我将替换所有东西”。 What am I doing wrong?
我究竟做错了什么?
Try this instead试试这个
$pattern = '/^0$/';
$replacement = ' ';
$report_output.= '
<td>'.preg_replace($pattern, $replacement, round($row[$win_count])).'</td>
';
^
means match start of string ^
表示匹配字符串的开始0
is match one 0 0
是匹配一 0$
means match end of string $
表示匹配字符串的结尾So it will only match '0'
one zero start to finish and not something like this hell0
the end 0 wont be matched because the l
is not the start of the string.所以它只会匹配
'0'
一个零开始到结束而不是像这样的东西hell0
结束 0 不会被匹配,因为l
不是字符串的开始。
Your question is confusing if you want any 0 anywhere then use this instead如果您想在任何地方使用任何 0 然后使用它,您的问题会令人困惑
$pattern = '/0/';
With delimiters.带分隔符。
You can use a simple shorthand ternary.您可以使用简单的速记三元组。
Generally: $variable?: ''
通常:
$variable?: ''
If it is a false value, then the fallback empty string will be used.如果它是一个假值,那么将使用后备空字符串。
printf(
'"%s" vs "%s"',
round($row[$win_count]),
round($row[$win_count]) ?: ''
);
Output: Output:
"0" vs ""
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.