how to replace(($24.39)) as 24.39 using preg_replace in php?
Asked
Active
Viewed 647 times
1
-
7Why don't you just use str_replace? The pattern is `(($` and `))`, I see no reason to use regular expressions for that. – Michael J.V. May 03 '11 at 11:41
-
I agree with Michael. In this case using str_replace would be good. – Nobita May 03 '11 at 11:42
4 Answers
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
Related but not applicable as a solution for your given string: PHP: unformat money
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
1
Regex are expensive. Use:
$str = '(($24.39))';
$str = str_replace('(($', '', $str);
$str = str_replace('))', '', $str);

Shoe
- 74,840
- 36
- 166
- 272