PHP에서 문자열 바꾸기

Minahil Noor 2020년12월25일
PHP에서 문자열 바꾸기

이 기사에서는 PHP에서 문자열의 일부를 대체하는 방법을 소개합니다.

str_replace()함수를 사용하여 PHP에서 문자열 부분 바꾸기

PHP에서 문자열의 일부를 대체하는 특수 함수는 str_replace()입니다. 이 함수는 주어진 하위 문자열을 검색하여 제공된 값으로 바꿉니다. 이 함수를 사용하기위한 올바른 구문은 다음과 같습니다.

str_replace($search, $replace, $subject, $count);

str_replace()함수에는 4 개의 매개 변수 만 있습니다. 매개 변수의 세부 사항은 다음과 같습니다.

변수 기술
$search 필수 주어진 문자열 또는 배열에서 검색하려는 문자열 또는 배열입니다. 이$search 문자열 또는 배열은 주어진$replace 매개 변수로 대체됩니다.
$replace 필수 $search위치에 배치 될 문자열 또는 배열입니다.
$subject 필수 하위 문자열을 검색하고 대체 할 문자열 또는 배열입니다.
$count 선택 과목 주어진 경우 수행 된 교체를 계산합니다.

이 함수는 수정 된 문자열 또는 배열을 반환합니다. 아래 프로그램은str_replace()함수를 사용하여 PHP에서 문자열의 일부를 대체하는 방법을 보여줍니다.

<?php
$mystring = "This is my string.";
echo("This is the string before replacement: ");
echo($mystring);
echo("\n");
$mynewstring = str_replace(" my ", " ", $mystring);
echo("Now, this is the string after replacement: ");
echo($mynewstring);
?>

출력:

This is the string before replacement: This is my string.
Now, this is the string after replacement: This is string.

함수가 수정 된 문자열을 반환했습니다.

이제$count 매개 변수를 전달하면 교체 한 횟수를 계산합니다.

<?php
$mystring = "This is my string.";
echo("This is the string before replacement: ");
echo($mystring);
echo("\n");
$mynewstring = str_replace(" my ", " ", $mystring, $count);
echo("Now, this is the string after replacement: ");
echo($mynewstring);
echo("\n");
echo("The number of replacements is: ");
echo($count);
?>

출력:

This is the string before replacement: This is my string.
Now, this is the string after replacement: This is string.
The number of replacements is: 1

출력은 함수가 한 번만 교체 함을 보여줍니다. 이는 $search문자열이 전달 된 문자열에서 한 번만 나타났음을 의미합니다.

관련 문장 - PHP String