💻 자주 쓰는 PHP 함수

[PHP 함수] str_replace() 함수 사용하여 문자열 조작하기

rhandy 2025. 3. 17. 07:10
728x90

PHP에서 문자열을 대체하는 가장 기본적인 함수 중 하나가 str_replace()입니다. 이 함수는 특정 문자열을 찾아 다른 문자열로 바꾸는 데 사용되며, 대소문자를 구분하지 않는 대체, 여러 문자열 변경, 특수문자 제거 등 다양한 방식으로 활용할 수 있습니다. 이 글에서는 str_replace() 함수의 사용법과 다양한 활용 예제를 살펴보고, 실제 웹 개발에서 어떻게 유용하게 활용할 수 있는지 자세히 설명하겠습니다.


1. str_replace() 함수란?

str_replace() 함수는 특정 문자열을 찾아 다른 문자열로 치환하는 기능을 합니다. 검색 대상이 배열일 경우, 배열 내 모든 요소에서 지정된 문자열을 찾아 변경할 수도 있습니다.

📌 기본 문법

str_replace(mixed $search, mixed $replace, mixed $subject, int &$count = null): string|array
  • search (필수): 찾을 문자열
  • replace (필수): 변경할 문자열
  • subject (필수): 검색할 문자열 또는 배열
  • count (선택): 치환된 횟수를 저장할 변수 (참조 방식)

📌 반환값

 

  • 변경된 문자열을 반환
  • $subject가 배열이면, 배열 내 모든 요소에서 문자열을 변경 후 반환

2. 기본 사용법과 예제

✅ 단순 문자열 치환

$text = "Hello, World!";
$new_text = str_replace("World", "PHP", $text);
echo $new_text; // 출력: Hello, PHP!

✅ 여러 개의 문자열 대체하기

$text = "I love apples and oranges.";
$new_text = str_replace(["apples", "oranges"], ["bananas", "grapes"], $text);
echo $new_text; // 출력: I love bananas and grapes.

✅ 대소문자 구분하지 않고 치환하기

기본적으로 str_replace()는 대소문자를 구분합니다. 대소문자를 구분하지 않고 치환하려면 str_ireplace()를 사용해야 합니다.

$text = "Hello, World!";
$new_text = str_ireplace("world", "PHP", $text);
echo $new_text; // 출력: Hello, PHP!

✅ 특정 문자 제거하기

$text = "2024-06-15";
$new_text = str_replace("-", "", $text);
echo $new_text; // 출력: 20240615

✅ 여러 문자 제거하기

$text = "Hello, (World)!";
$new_text = str_replace(["(", ")", "!"], "", $text);
echo $new_text; // 출력: Hello, World

✅ 대체할 횟수 계산하기

$text = "apple, apple, apple";
$count = 0;
$new_text = str_replace("apple", "banana", $text, $count);
echo $new_text; // 출력: banana, banana, banana
echo "변경된 횟수: $count"; // 출력: 변경된 횟수: 3

✅ 배열에서 사용하기

$array = ["I love apples", "Apples are tasty", "Green apples are the best"];
$new_array = str_replace("apples", "bananas", $array);
print_r($new_array);
/* 출력:
Array (
    [0] => I love bananas
    [1] => Bananas are tasty
    [2] => Green bananas are the best
)
*/

✅ 특수문자 제거하기

$text = "Hello! How's it going? #Great";
$new_text = str_replace(["!", "'", "#"], "", $text);
echo $new_text; // 출력: Hello Hows it going Great

✅ HTML 태그 대체하기

$html_text = "<p>This is a <strong>bold</strong> text.</p>";
$clean_text = str_replace(["<p>", "</p>", "<strong>", "</strong>"], "", $html_text);
echo $clean_text; // 출력: This is a bold text.

3. 다양한 활용 방안

✅ SEO 친화적인 URL 변환

$title = "PHP String Replace Function";
$url_friendly = str_replace(" ", "-", strtolower($title));
echo $url_friendly; // 출력: php-string-replace-function

✅ 사용자 입력 필터링

$input = "I hate spam messages!";
$filtered = str_replace("spam", "***", $input);
echo $filtered; // 출력: I hate *** messages!

✅ 블로그 게시글 자동 태그 추가 (보안 강화)

$blog_content = "Learn PHP, JavaScript, and Python!";
$keywords = ["PHP" => "<strong>PHP</strong>", "JavaScript" => "<strong>JavaScript</strong>", "Python" => "<strong>Python</strong>"];
$highlighted_content = str_replace(array_keys($keywords), array_values($keywords), $blog_content);
echo $highlighted_content;

// 출력 : Learn <strong>PHP</strong>, <strong>JavaScript</strong>, and <strong>Python</strong>!

 

✅ 이메일 주소 보호

스팸 봇이 이메일 주소를 수집하는 것을 방지하려면 이메일을 특수 문자로 변환할 수 있습니다.

$email = "user@example.com";
$protected_email = str_replace(["@", "."], [" [at] ", " [dot] "], $email);

echo $protected_email;

// 출력 : user [at] example [dot] com

✅ 대량 문자열 교체 (템플릿 엔진)

PHP에서 템플릿 시스템을 만들 때 변수 치환 기능을 쉽게 구현할 수 있습니다.

$template = "안녕하세요, {name}님! 오늘은 {date} 입니다.";
$values = ["{name}" => "홍길동", "{date}" => date("Y-m-d")];

$message = str_replace(array_keys($values), array_values($values), $template);
echo $message;

// 출력 : 안녕하세요, 홍길동님! 오늘은 2025-03-11 입니다.

4. str_replace() 사용 시 주의할 점

❗ str_replace()의 성능 문제

  • 문자열 길이가 길거나, 대량의 데이터를 처리할 경우 성능 저하가 발생할 수 있습니다.
  • 이 경우 preg_replace() 또는 strtr()를 고려하는 것이 좋습니다.

❗ 대소문자 구분 문제

  • 기본적으로 str_replace()는 대소문자를 구분합니다.
  • str_ireplace()를 사용하면 대소문자 관계없이 치환할 수 있습니다.
str_ireplace("hello", "hi", "Hello World!"); // "hi World!"

❗ 정규식이 필요할 경우

  • str_replace()는 정규식을 지원하지 않습니다. 정규식을 사용하려면 preg_replace()를 사용해야 합니다.
$text = "전화번호: 010-1234-5678";
$masked = preg_replace("/\d{4}-\d{4}/", "****-****", $text);
echo $masked; // 전화번호: 010-****-****

5. 정리

str_replace() 함수는 PHP에서 가장 유용한 문자열 치환 함수 중 하나이며, 간단한 치환부터 배열 처리까지 다양한 기능을 제공합니다. 하지만 대량 데이터 처리 시 성능을 고려해야 하며, 정규식이 필요할 경우 preg_replace()를 사용할 수도 있습니다. 이를 활용하면 SEO 최적화, 필터링 시스템, 보안 강화, 이메일 보호, 템플릿 엔진 등 다양한 기능을 구현할 수 있습니다.

 

728x90