1


I am trying to get rid of - in a string like 50-000 and output 50000 but unable to using strstr. Here is the code I tried

$addr = "50-000";
echo $addr = strtr($addr, "-", "");

Any clues whats going wrong here.

Thanks.

pal4life
  • 3,210
  • 5
  • 36
  • 57
  • `str_replace` is a lot faster than `strtr`, not that it it would probably matter in the real world –  Jan 28 '14 at 21:00
  • For that I referred to this discussion http://stackoverflow.com/questions/8177296/when-to-use-strtr-vs-str-replace – pal4life Jan 28 '14 at 21:09

3 Answers3

3

Just use str_replace()

echo str_replace('-', '', "50-000");
John Conde
  • 217,595
  • 99
  • 455
  • 496
3

try this

echo str_replace("-","","50-000");

Mohammed Sufian
  • 1,743
  • 6
  • 35
  • 62
0

According to the manual:

string strtr ( string $str , string $from , string $to )

If given three arguments, ... If from and to have different lengths, the extra characters in the longer of the two are ignored. The length of str will be the same as the return value's.

Since "-" is longer than "", the character is ignored.
As this three-arguments call will return the same string length, it may not help you to shorten the string from "50-000" to "50000".

Instead, you may try the two-arguments call, where the returned string length may differ:

string strtr ( string $str , array $replace_pairs )

E.g.

$addr = "50-000";
echo $addr = strtr($addr, array("-"=>""));
// returns "50000"

In case you are interested to know more about strtr() and str_replace():
PHP strtr vs str_replace benchmarking
When to use strtr vs str_replace?

Community
  • 1
  • 1
yhd.leung
  • 1,162
  • 1
  • 18
  • 27