카테고리 없음
[PHP] preg_match_all 문제 내부의 preg_replace
행복을전해요
2020. 12. 30. 22:47
원래 패턴 내에서 하위 패턴을 찾기 위해 정규 표현식을 강화하는 것이 가장 좋습니다. 그렇게하면 preg_replace ()를 호출하여 끝낼 수 있습니다.
$new_file_contents = preg_replace('/regular(Exp)/', 'replacement', $content);
정규식 내에서 "()"를 사용하여 수행 할 수 있습니다. "정규 표현식 서브 패턴"에 대한 빠른 구글 검색 결과 이 .
-------------------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
정규식 일치를 바꾸고 결과를에 저장하려는 경우 new_file.ext
필요한 모든 것은 다음과 같습니다.
$content = file_get_contents('file.ext');
$content = preg_replace('/match/', 'replacement', $content);
file_put_contents('new_file.ext', $content);
출처
https://stackoverflow.com/questions/2002906