[英]How to remove all leading zeroes in a string
如果我有一個字符串
00020300504
00000234892839
000239074
我怎樣才能擺脫前導零,以便我只有這個
20300504
234892839
239074
請注意,上面的數字是隨機生成的。
ltrim
:
$str = ltrim($str, '0');
(string)((int)"00000234892839")
類似於另一個建議,除了不會抹去實際的零:
if (ltrim($str, '0') != '') {
$str = ltrim($str, '0');
} else {
$str = '0';
}
或者按照建議(從 PHP 5.3 開始),可以使用速記三元運算符:
$str = ltrim($str, '0') ?: '0';
不知道為什么人們要用這么復雜的方法來實現這么簡單的事情! 和正則表達式? 哇!
給你,最簡單和最簡單的方法(如下解釋: https : //nabtron.com/kiss-code/ ):
$a = '000000000000001';
$a += 0;
echo $a; // will output 1
您可以在變量中添加“+”,
例子 :
$numString = "0000001123000";
echo +$numString;
已經提出了正則表達式,但不正確:
<?php
$number = '00000004523423400023402340240';
$withoutLeadingZeroes = preg_replace('/^0+/', '', $number)
echo $withoutLeadingZeroes;
?>
然后輸出是:
4523423400023402340240
正則表達式的背景: ^
表示字符串的開始,而+
號表示更多或沒有前面的符號。 因此,正則表達式^0+
匹配字符串開頭的所有零。
我不認為 preg_replace 是答案.. 舊線程,但碰巧今天正在尋找這個。 ltrim 和 (int) 鑄造是贏家。
<?php
$numString = "0000001123000";
$actualInt = "1123000";
$fixed_str1 = preg_replace('/000+/','',$numString);
$fixed_str2 = ltrim($numString, '0');
$fixed_str3 = (int)$numString;
echo $numString . " Original";
echo "<br>";
echo $fixed_str1 . " Fix1";
echo "<br>";
echo $fixed_str2 . " Fix2";
echo "<br>";
echo $fixed_str3 . " Fix3";
echo "<br>";
echo $actualInt . " Actual integer in string";
//output
0000001123000 Origina
1123 Fix1
1123000 Fix2
1123000 Fix3
1123000 Actual integer in tring
我用這種方式固定。
它非常簡單。 只傳遞一個字符串,它刪除字符串的零開頭。
function removeZeroString($str='')
{
while(trim(substr($str,0,1)) === '0')
{
$str = ltrim($str,'0');
}
return $str;
}
一個簡短的技巧可以是使用 round() 它將刪除前導零。
echo round('00020300504'); //20300504
Ajay Kumar 提供了最簡單的echo +$numString; 我使用這些:
echo round($val = "0005");
echo $val = 0005;
//both output 5
echo round($val = 00000648370000075845);
echo round($val = "00000648370000075845");
//output 648370000075845, no need to care about the other zeroes in the number
//like with regex or comparative functions. Works w/wo single/double quotes
實際上,任何數學函數都會從“字符串”中獲取數字並像這樣對待它。 它比任何正則表達式或比較函數都要簡單得多。 我在 php.net 上看到的,不記得在哪里了。
假設您希望刪除連續的三個或更多零,並且您的示例是一個字符串:
$test_str ="0002030050400000234892839000239074";
$fixed_str = preg_replace('/000+/','',$test_str);
如果我的假設不成立,您可以使正則表達式模式適合您的需要。
這個幫助?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.