2014-09-20 2 views
0

정규식뿐만 아니라 새로운 작업입니다. 나는 PHP를 사용하고 있습니다.정규 표현식을 사용하여 문자열에서 데이터를 추출합니다.

다음 문자열의 경우 보고서 번호를 추출하고 싶습니다.

Dear Patient! (patient name) Your Reports(report number) has arrived. 

나를 정규 표현식으로 만드는 사람이 도와 줄 수 있습니까?

$str ='Dear Patient! (P.JOHN) Your Reports (REPORTNO9) has arrived.'; 
$str = str_replace('(', '', $str); 
$str = str_replace(')', '', $str); 
preg_match('/Reports\s*(\w+)/', $str, $match); 
echo $match[1]; //=> "REPORTNO9" 
+0

http://www.regular-expressions.info/ 먼저 직접 작성해야합니다. – andy

+0

실생활의 예를 제공해주십시오. 즉 '환자 이름'과 '신고 번호'가 어떻게 생겼는지를 알 수 있습니다. –

+0

@andy : 고맙습니다.이 질문을하는 것이 적절한 곳이 아니라는 것을 알고 있습니다. 나는 배울 수있는 충분한 시간이 없다. 나는 나 자신을 배울 것입니다. 나는이 직업을 더 이상 배우지 못한다. –

답변

1

정규식

/Dear (\w+)! Your Reports(.*?)(?=has arrived)/ 

PHP 사용

<?php 
$subject = 'Dear Patient! Your Reports(report number) has arrived.'; 
if (preg_match('/Dear (\w+)! Your Reports(.*?)(?=has arrived)/', $subject, $regs)) { 
    var_dump($regs); 
} 
를 :

가 해결 주셔서 감사합니다

결과

array(3) { 
    [0]=> 
    string(42) "Dear Patient! Your Reports(report number) " 
    [1]=> 
    string(7) "Patient" 
    [2]=> 
    string(16) "(report number) " 
} 

설명

" 
Dear\    # Match the characters “Dear ” literally 
(    # Match the regular expression below and capture its match into backreference number 1 
    \w    # Match a single character that is a “word character” (letters, digits, etc.) 
     +     # Between one and unlimited times, as many times as possible, giving back as needed (greedy) 
) 
!\ Your\ Reports # Match the characters “! Your Reports” literally 
(    # Match the regular expression below and capture its match into backreference number 2 
    .     # Match any single character that is not a line break character 
     *?    # Between zero and unlimited times, as few times as possible, expanding as needed (lazy) 
) 
(?=    # Assert that the regex below can be matched, starting at this position (positive lookahead) 
    has\ arrived  # Match the characters “has arrived” literally 
) 
" 
+0

+1입니다. – Mikk

+0

많은 의무가 있습니다! :) –

0
당신이 정규식을 사용하지 않아도 당신은이 같은 문자열의 특정 부분을 추출하는 "분할()"를 사용할 수 있습니다

:

<?php 
    $my_string = ""; // Put there you string 
    $array_my_string = array(); 

    $array_my_string = split('Reports', $my_string); 

    $tempResult = array_my_string[1]; // Will contains "(report number) has arrived." 

    $array_my_string = split(' has arrived', $tempResult); 

    $finalResult = $array_my_result[0]; // Will contains "(report number)" 
?> 
관련 문제