preg_match_all 문제 내부의 preg_replace
-
18-09-2019 - |
문제
내 데이터 파일에서 특정 블록을 찾아 내부를 바꾸려고 노력하고 있습니다. 그 후 모든 것을 (대체 된 데이터와 함께) 새 파일에 넣습니다. 현재 내 코드는 다음과 같습니다.
$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
?
고맙습니다!
해결책
원래 패턴 내에서 소환자를 찾기 위해 정규 표현을 강화하는 것이 가장 좋습니다. 그렇게하면 preg_replace ()를 호출하고 완료 할 수 있습니다.
$new_file_contents = preg_replace('/regular(Exp)/', 'replacement', $content);
이것은 정규 표현 내에서 "()"로 수행 할 수 있습니다. "정규 표현 서브 패턴"에 대한 빠른 Google 검색으로 인해 이것.
다른 팁
당신은 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);
나는 당신의 문제를 이해하는지 잘 모르겠습니다. 아마도 다음의 예를 게시 할 수 있습니까?
- file.ext, 원본 파일
- 사용하고 싶은 정규식과 매치를 대체하려는 것
- new_file.ext, 원하는 출력
당신이 그냥 읽고 싶다면 file.ext
, REGEX 매치를 교체하고 결과를 저장하십시오. new_file.ext
, 당신의 모든 필요는 다음과 같습니다.
$content = file_get_contents('file.ext');
$content = preg_replace('/match/', 'replacement', $content);
file_put_contents('new_file.ext', $content);
제휴하지 않습니다 StackOverflow