I need a help in regex php. If in a string find number after some character. get that number and replace it with after applying math. Like currency convert.
I applied this regex https://regex101.com/r/KhoaKU/1
([^\?])AUD (\d)
regex not correct I want all matched number here only it's matched 40 but there also 20.00, 9.95 etc.. I am trying to get all. and convert them.
function simpleConvert($from,$to,$amount)
{
$content = file_get_contents('https://www.google.com/finance/converter?a='.$amount.'&from='.$from.'&to='.$to);
$doc = new DOMDocument;
@$doc->loadHTML($content);
$xpath = new DOMXpath($doc);
$result = $xpath->query('//*[@id="currency_converter_result"]/span')->item(0)->nodeValue;
return $result;
}
$pattern_new = '/([^\?]*)AUD (\d*)/';
if ( preg_match ($pattern_new, $content) )
{
$has_matches = preg_match($pattern_new, $content);
print_r($has_matches);
echo simpleConvert("AUD","USD",$has_matches);
}
If you just need to get all those values and convert them with simpleConvert
, use a regex for integer/float numbers and after getting the values, pass the array to array_map
:
$pattern_new = '/\bAUD (\d*\.?\d+)/';
preg_match_all($pattern_new, $content, $vals);
print_r(array_map(function ($a) { return simpleConvert("AUD", "USD", $a); }, $vals[1]));
See this PHP demo.
Pattern details:
\b
- a leading word boundaryAUD
- a literal char sequence
- a space(\d*\.?\d+)
- Group 1 capturing 0+ digits, an optional .
and then 1+ digits.Note that $m[1]
passed to the simpleConvert
function holds the contents of the first (and only) capturing group.
If you want to change those values inside the input text, I suggest the same regex in a preg_replace_callback
:
$content = "The following fees and deposits are charged by the property at time of service, check-in, or check-out.\r\n\r\nBreakfast fee: between AUD 9.95 and AUD 20.00 per person (approximately)\r\nFee for in-room wireless Internet: AUD 0.00 per night (rates may vary)\r\nFee for in-room high-speed Internet (wired): AUD 9.95 per night (rates may vary)\r\nFee for high-speed Internet (wired) in public areas: AUD 9.95 per night (rates may vary)\r\nLate check-out fee: AUD 40\r\nRollaway beds are available for an additional fee\r\nOnsite credit card charges are subject to a surcharge\r\nThe above list may not be comprehensive. Fees and deposits may not include tax and are subject to change.";
$pattern_new = '/\bAUD (\d*\.?\d+)/';
$res = preg_replace_callback($pattern_new, function($m) {
return simpleConvert("AUD","USD",$m[1]);
}, $content);
echo $res;
See the PHP demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With