Get a number from a string after a certain character and convert this number

I need help with regex php. If in the string find the number after some character. get this number and replace it after applying math. How currency conversion.

I applied this regex https://regex101.com/r/KhoaKU/1

([^ \?]) AUD (\ d)

regex not correct I want all the coinciding numbers here to match only 40, but there are also 20.00, 9.95, etc. I'm trying to get everything. 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); } 
+5
source share
1 answer

If you just need to get all these values ​​and convert them using simpleConvert , use the regular expression 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 .

Template Details :

  • \b - upper word boundary
  • AUD - literal char sequence
  • - space
  • (\d*\.?\d+) - group 1, fixing digits 0+, optional . and then 1 + numbers.

Note that $m[1] , passed to the simpleConvert function, contains the contents of the first (and only) capture group.

If you want to change these values ​​in the input text, I suggest the same regular expression in 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 PHP demo

+3
source

Source: https://habr.com/ru/post/1262627/


All Articles