2017-01-11 7 views
5

정규식에서 도움이 필요합니다. 문자열의 일부 문자 뒤에 숫자를 찾으십시오. 그 숫자를 얻고 수학을 적용한 후에 그것을 대체하십시오. 통화 변환처럼.특정 문자 다음에 나오는 문자열에서 숫자를 가져 와서 그 숫자를 변환하십시오.

https://regex101.com/r/KhoaKU/1

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

정규식 여기에만 40 유사한 것 모두 유사한 참조 할 해결되지이 정규 표현식을 적용하지만 거기 또한 20.00, 9.95 등. 나는 모든 것을 얻으려고 노력하고있다. 그들을 변환하십시오. 그냥 모든 값을 얻을 simpleConvert로 변환, 정수/부동 소수점 숫자와 값을 받고 후 정규식을 사용해야하는 경우

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); 
} 
+0

을보기를 일치시킬 필요가있는 값은'이다 40'? 정규 표현식이 맞습니까? –

+0

정확히 무엇이 문제입니까? – jeroen

+0

@ WiktorStribiżew 정규식이 맞지 않습니다. 여기 일치하는 모든 숫자를 원하면 40과 일치하지만 20.00, 9.95 등도 있습니다. 모두 얻으려고합니다. 그들을 변환하십시오. –

답변

3

, 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])); 

참조 this PHP demo.

패턴 자세한 사항 :

  • \b - 선도적 인 단어 경계
  • AUD - 리터럴 문자 순서
  • - 공간
  • (\d*\.?\d+) - 그룹 1 0+ 자리 캡처 선택 사항 인 . 다음에 1 자리 이상. $m[1]simpleConvert 함수에 전달 된

노트는 최초로 유일한 캡처 그룹의 콘텐츠를 보유하고있다.

당신이 입력 텍스트 내에서 그 값을 변경하려면

, 나는이 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; 

는 그래서 PHP demo

+1

제안에 따라 preg_replace_callback을 사용했습니다. 그것은 나를 위해 일했습니다. 감사. –