10분끄적임

php preg_replace 함수

닮은 2022. 11. 30. 10:24

preg_replace는 정규식 pattern을 replacement로 치환한 값을 돌려주는 함수인데요 pattern과 replacement가 배열이라 여러 패턴을 치환할 수 있어요. 그런데! 

 

물론 이렇게 이상하게 쓰는 사람은 없겠지만

<?php
$string = 'The quick brown fox jumped over the lazy dog.';
$patterns = array();
$patterns[0] = '/quick/';
$patterns[1] = '/brown/';
$patterns[2] = '/fox/';
$replacements = array();
$replacements[2] = 'bear';
$replacements[1] = 'black';
$replacements[0] = 'slow';
echo preg_replace($patterns, $replacements, $string);
?>

이렇게 했을때 결과 값이 

The slow black bear jumped over the lazy dog.

가 아니라 

The bear black slow jumped over the lazy dog.

가 되는데요, php는 인덱스 값의 순서에 따라서 치환을 하는 것이 아니고, 배열의 값이 생성된 순서대로 치환을 하기 때문에 $patterns[0]의 카운터 파트너는 $replacements[0]이 아니라 $replacements[2]가 되기 때문이라고 합니다. 정말 요상하게 작동 하네요.. 

 

출처: 생활코딩 (https://opentutorials.org/course/62/5141)