Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove 0's from a string

Tags:

php

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 trimbecause it would also remove the ending 0 but since I forgot to add that the answer I got is great :)

like image 675
Thomaschaaf Avatar asked Apr 01 '09 21:04

Thomaschaaf


People also ask

How do I remove 0 from a string in Python?

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.

How do you remove leading zeros from a string in C++?

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.


3 Answers

$ php -r 'echo trim("0string0", "0") . "\n";'
string

For the zero padded number in the example:

$ php -r 'echo ltrim("00023460", "0") . "\n";'
23460
like image 147
ashawley Avatar answered Sep 24 '22 05:09

ashawley


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'
like image 44
David Snabel-Caunt Avatar answered Sep 24 '22 05:09

David Snabel-Caunt


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';

like image 43
OIS Avatar answered Sep 23 '22 05:09

OIS