Thomaschaaf
Thomaschaaf

Reputation: 18196

How to remove 0's from a string

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 :)

Upvotes: 7

Views: 4436

Answers (5)

ashawley
ashawley

Reputation: 4283

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

For the zero padded number in the example:

$ php -r 'echo ltrim("00023460", "0") . "\n";'
23460

Upvotes: 16

OIS
OIS

Reputation: 10033

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

Upvotes: 2

David Snabel-Caunt
David Snabel-Caunt

Reputation: 58361

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'

Upvotes: 2

Gumbo
Gumbo

Reputation: 655239

Sure it does (see second parameter $charlist):

trim('000foo0bar000', '0')  // 'foo0bar'

Upvotes: 1

Mark Biek
Mark Biek

Reputation: 150769

Take a look at str_replace

print str_replace( '0', '', "This0string0needs0spaces");

Upvotes: 1

Related Questions