I'm looking at the function trim
but that unfortunately does not remove "0"s how do I add that to it? Should I use str_replace
?
EDIT: The string I wanted to modify was a message number which looks like this: 00023460
The function ltrim("00023460", "0")
does just what I need :) obviously I would not want to use the regular trim
because it would also remove the ending 0 but since I forgot to add that the answer I got is great :)
The lstrip() method to remove leading zeros When used, it automatically removes leading zeros ( only ) from the string. Note that this works for numbers and all characters accepted as a string. However, another method strip() will remove the leading and ending characters from the string. Python lstrip() docs.
Using Stoi() Method stoi() function in C++ is used to convert the given string into an integer value. It takes a string as an argument and returns its value in integer form. We can simply use this method to convert our string to an integer value which will remove the leading zeros.
$ php -r 'echo trim("0string0", "0") . "\n";'
string
For the zero padded number in the example:
$ php -r 'echo ltrim("00023460", "0") . "\n";'
23460
The trim function only removes characters from the beginning and end of a string, so you probably need to use str_replace.
If you only need to remove 0s from the beginning and end of the string, you can use the following:
$str = '0000hello00';
$clean_string = trim($str, '0'); // 'hello'
This should have been here from the start.
EDIT: The string I wanted to modify was a message number which looks like this: 00023460
The best solution is probably this for any integer lower then PHP_INT_MAX
$number = (int) '00023460';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With