1

how to replace(($24.39)) as 24.39 using preg_replace in php?

alex
  • 479,566
  • 201
  • 878
  • 984
Nirav Jain
  • 5,088
  • 5
  • 40
  • 61

4 Answers4

5

Instead of preg_replace or str_replace you could also use filter_var:

echo filter_var(
    '(($24.39))', 
    FILTER_SANITIZE_NUMBER_FLOAT, 
    FILTER_FLAG_ALLOW_FRACTION
); // 24.39

demo on codepad

Related but not applicable as a solution for your given string: PHP: unformat money

Community
  • 1
  • 1
Gordon
  • 312,688
  • 75
  • 539
  • 559
2

you could try:

$str = "(($24.39))";
$str = preg_replace('/[^\.\d]/',"",$str);
echo $str;
Ian Wood
  • 6,515
  • 5
  • 34
  • 73
  • would concur with Michael and Niobita - IF that is the consistent pattern. str_replace is much more efficient... – Ian Wood May 03 '11 at 11:46
2

If you had a large string with multiple occurrences and wanted to replace those in that pattern only...

$str = preg_replace('/\(\((\$\d+\.\d+)\)\)/', '$1', $str);

CodePad.

If you wanted to make the decimal optional, you could change the \.\d+ to (?:\.\d+)?.

alex
  • 479,566
  • 201
  • 878
  • 984
1

Regex are expensive. Use:

$str = '(($24.39))';
$str = str_replace('(($', '', $str);
$str = str_replace('))', '', $str);
Shoe
  • 74,840
  • 36
  • 166
  • 272