2010-01-04 2 views
1

내 데이터 파일에서 특정 블록을 찾아 내고 그 중 일부를 대체하려고합니다. 그런 다음 대체 된 데이터로 모든 것을 새 파일에 넣습니다. 현재 코드는 다음과 같습니다.preg_replace within preg_match_all 문제

$content = file_get_contents('file.ext', true); 

//find certain pattern blocks first 
preg_match_all('/regexp/su', $content, $matches); 

foreach ($matches[0] as $match) { 
    //replace data inside of those blocks 
    preg_replace('/regexp2/su', 'replacement', $match); 
} 

file_put_contents('new_file.ext', return_whole_thing?); 

이제 문제는 return_whole_thing하는 방법을 모른다는 것입니다. 기본적으로 file.ext와 new_file.ext는 대체 된 데이터를 제외하고 거의 동일합니다. 어떤 제안이 return_whole_thing의 자리에 있어야합니까?

감사합니다.

답변

0

정규 표현식을 강화하여 원래 패턴 내에서 하위 패턴을 찾는 것이 가장 좋습니다. 그렇게하면 preg_replace()를 호출하고 완료 할 수 있습니다.

$new_file_contents = preg_replace('/regular(Exp)/', 'replacement', $content); 

정규식 내에서 "()"를 사용하여 수행 할 수 있습니다. "regular expression subpatterns"에 대한 빠른 Google 검색 결과는 this입니다.

2

preg_replace가 필요하지 않습니다. 이미 성냥을 가졌기 때문에 정상적인 str_replace를 다음과 같이 사용할 수 있습니다.

$content = file_get_contents('file.ext', true); 

//find certain pattern blocks first 
preg_match_all('/regexp/su', $content, $matches); 

foreach ($matches[0] as $match) { 
    //replace data inside of those blocks 
    $content = str_replace($match, 'replacement', $content) 
} 

file_put_contents('new_file.ext', $content); 
0

잘 모르겠습니다. 당신은 아마의 예를 게시 할 수 없습니다 :

  • file.ext를 원본 파일
  • 당신이 사용하고자하는 정규식과 당신이
  • new_file.ext, 원하는 출력과 일치를 대체 할을

그냥, file.ext을 읽을 정규식 일치를 교체하고 new_file.ext에 결과를 저장하려면, 모든 필요가 :

$content = file_get_contents('file.ext'); 
$content = preg_replace('/match/', 'replacement', $content); 
file_put_contents('new_file.ext', $content);