여러개 preg_replace 질문
본문
$stx = preg_replace("/(1)/", "a", $stx);
이런게 있다고 할때
$stx = preg_replace("/(2)/", "b", $stx);
$stx = preg_replace("/(3)/", "c", $stx);
$stx = preg_replace("/(4)/", "d", $stx);
.
.
.
이런식으로 쭉 만들고 싶은데 이걸 한줄로 표현 가능할까요?
답변 2
for문 쓰시면됩니다
$count = 7;//반복할갯수
for($i=0;$i<$count;$i++){
$stx = preg_replace("/(".$i.")/", "b", $stx);
}
찾는 값과 바꿀 값을 모두 배열로 넘길 수 있습니다.
성능면에서 조금 이득을 보지 않을까 짐작합니다.
https://www.php.net/manual/en/function.preg-replace.php
<?php
$string = 'The quick brown fox jumps 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);
?>
!-->
답변을 작성하시기 전에 로그인 해주세요.