
str_replace 함수는 한 번에 하나의 문자열만 교체할 수 있습니다.
다중 교체를 위해서는 str_replace 함수를 여러 번 호출하거나, 다른 함수를 사용해야 합니다.
예를 들어, str_replace 함수를 여러 번 호출하는 방법은 다음과 같습니다.
#hostingforum.kr
php
$text = "Hello, world! Hello again!";
$result = str_replace("Hello", "Goodbye", $text);
$result = str_replace("world", "earth", $result);
echo $result;
또는, preg_replace 함수를 사용하는 방법은 다음과 같습니다.
#hostingforum.kr
php
$text = "Hello, world! Hello again!";
$result = preg_replace("/Hello|world/", "Goodbye", $text);
echo $result;
또는, str_replace 함수를 여러 개의 문자열을 교체할 수 있도록 확장한 함수를 사용하는 방법은 다음과 같습니다.
#hostingforum.kr
php
function multi_replace($text, $replacements) {
foreach ($replacements as $key => $value) {
$text = str_replace($key, $value, $text);
}
return $text;
}
$text = "Hello, world! Hello again!";
$replacements = array("Hello" => "Goodbye", "world" => "earth");
$result = multi_replace($text, $replacements);
echo $result;
2025-06-13 07:11