Reputation: 2519
I'm going round and round in circles here. I have this string:
document.write('£222,648.43');
and I want to use php/regexp to end up with 222,648.43
Here's the closest I've got so far:
preg_match('/\(\'(.*)\'\)/', $str, $matches);
var_dump($matches);
That vardump gives me:
array (size=2)
0 => string '('£222,648.43')' (length=15)
1 => string '£222,648.43' (length=11)
So.. how to get rid of that '£' char please?
Also, as a bonus to help me learn more about regexp, why are 2 matches returned?
Thanks!
Upvotes: 0
Views: 106
Reputation: 3446
Here's an inverse way of doing it:
$string = "document.write('£222,648.43');";
$value = preg_replace("/[.,]*[^\d,.]+[.,]*/", "", $string);
Upvotes: 0
Reputation: 33341
The first match returned will be the match on the entire regex. The second will be the first capturing group, in parentheses.
If you want to eliminate the first character after the opening quote, you could use .
, just before the capturing section in parentheses, to match any character:
'/\(\'.(.*)\'\)/'
If you need to only eliminate it if it is the '£' character, you can add £?
, to optionally match the symbol, before entering the capturing group:
'/\(\'£?(.*)\'\)/'
If you need to eliminate other possible monetary symbols as that point, you can include them in a character class like [£$€¥₪₩₤﷼]
, such as:
'/\(\'[£$€¥₪₩₤﷼]?(.*)\'\)/'
Upvotes: 1
Reputation: 785196
You can use:
$str = "document.write('£222,648.43');";
echo preg_replace_callback("~^.*?\( *'([^']+)' *\).*?$~", function($m) {
return preg_replace('~[^\d,.]+~', '', $m[1]);
}, $str);
//=> 222,648.43
Upvotes: 0
Reputation: 39365
why are 2 matches returned?
Because one is from the captured group ( )
and the other one is for the whole pattern that matches with your string.
Using preg_replace
$content = preg_replace("/document\.write\('\D?([\d.,]+)'\);/", "$1", $content);
Here, its grabbing the number into group $1
and replace the whole string with this capture.
Alternately you can use this one too:
$content = preg_replace("/.*\('\D?([\d.,]+)'.*/", "$1", $content);
Upvotes: 1