2010-08-14 7 views
1

큰 텍스트 파일의 일부 샘플 텍스트입니다.PHP 정규식 대체 계산

...

(2, 1, 3, 2, 'text...','other text...', 'more text...', ...), 
(3, 1, 3, 2, 'text...','other text...', 'more text...', ...), 
(4, 1, 3, 2, 'text...','other text...', 'more text...', ...), 
(5, 1, 3, 2, 'text...','other text...', 'more text...', ...), 
(6, 1, 3, 2, 'text...','other text...', 'more text...', ...), 

는 지금은

(21, 1, 3, 2, 'text...','other text...', 'more text...', ...), 
(22, 1, 3, 2, 'text...','other text...', 'more text...', ...), 
(23, 1, 3, 2, 'text...','other text...', 'more text...', ...), 
(24, 1, 3, 2, 'text...','other text...', 'more text...', ...), 
(25, 1, 3, 2, 'text...','other text...', 'more text...', ...), 

preg_replace_callback()

이 솔루션을 것 같다 ... 첫 번째 열의 각 값에 19을 추가해야하지만 난 정말 정규 표현식에 익숙하지 않아요

답변

1
preg_replace_callback(
    '/(?<=\()(\d+)(?=,.+\),?\v)/', 
    function($match) { 
     return (string)($match[1]+19); 
    }, 
    $large_text 
); 
+0

감사합니다. (정규 표현식이 조금 어지럽다) – Glenn

+0

하지만 reg를 설명해 주시겠습니까? 당신이 사용한 표현? – Glenn

+0

'(? <= \()'는 선행 괄호를 대치 할 표현식의 시작을위한 큐로 찾는다.하지만 교체 될 표현식에는 포함되지 않지만'(\ d +)'로 표시되는 숫자 만 사용한다. 정규식의 나머지 부분은 숫자 뒤에 쉼표가 후행 괄호까지, 선택적 쉼표 (마지막 줄인 경우) 및 줄 바꿈 또는 '\ v'로 표시되는 세로 공백까지 있는지 확인합니다. . (? =,. + \),? \ v)'는 바꾸려는 표현식의 일부가 아니라는 것을 의미합니다. – stillstanding

0

이렇게하면 표준 입력으로 처리됩니다.

// Your function 
function add19($line) { 
    $line = preg_replace_callback(
     '/^\(([^,]*),/', 
     create_function(
      // single quotes are essential here, 
      // or alternative escape all $ as \$ 
      '$matches', 
      'return ("(" . (intval($matches[1])+19) . ",");' 
     ), 
     $line 
    ); 
    return $line; 
} 

// Example reading from stdin 
$fp = fopen("php://stdin", "r") or die("can't read stdin"); 
while (!feof($fp)) { 
    $line = add19(fgets($fp)); 
    echo $line; 
} 
fclose($fp);