PHP substr_replace()

PHPz
풀어 주다: 2024-08-29 12:50:50
원래의
483명이 탐색했습니다.

substr_replace()는 한 문자열의 일부를 다른 문자열로 바꾸는 데 사용되는 PHP의 또 다른 내장 함수입니다. 문자열 대체를 수행해야 하는 인덱스가 전달되어야 하는 입력 매개변수를 기반으로 합니다. 또한 교체를 수행해야 하는 인덱스까지의 길이를 제공할 수도 있습니다. 각 문자열을 바꾸기 위해 함수에 대한 입력 매개변수의 일부로 문자열 배열을 제공할 수 있습니다.

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

PHP substr_replace() 구문

다음은 구문입니다.

구문:

substr_replace($str, $replace, $st, $len)
로그인 후 복사

위 구문에서 볼 수 있듯이 이 함수는 4개의 매개변수를 허용하며 그 중 처음 3개 인수는 필수이고 마지막 매개변수는 선택사항입니다. 그리고 그 내용은 아래와 같습니다.

1. $str: 이는 필수 매개변수이며 대체가 이루어져야 하는 입력 문자열입니다.

2. $replace: 이는 또 다른 필수 매개변수이며 $str 매개변수를 대체하는 입력 문자열입니다.

3. $st: 이 매개변수도 필수 매개변수이며 교체를 시작해야 하는 인덱스 위치를 나타냅니다.

  • $st 매개변수가 양수인 경우 입력 문자열의 시작 부분부터 지정된 위치부터 교체가 시작됩니다.
  • $st 매개변수가 음수인 경우 입력 문자열 끝에서 지정된 위치부터 교체가 시작됩니다.
  • 이 $st 매개변수가 0이면 지정된 문자열의 첫 번째 문자부터 대체됩니다.

4. $len: 이것은 대체되어야 하는 문자 수를 제공하는 선택적 매개변수입니다. 이 $len 매개변수가 제공되지 않으면 $str 끝에서 교체가 자동으로 중지됩니다.

  • 이 매개변수는 $len이 양수인 경우 교체해야 하는 $str 조각의 길이를 설명합니다.
  • $len이 음수일 때 문자열 끝에서 교체를 중지해야 하는 총 문자 수를 알려줍니다.
  • 삽입하는 대신 $len 값이 0이면 교체를 수행합니다.

반환 값: 반환되는 값은 위의 매개변수에 따라 대체된 후 생성된 문자열입니다. 문자열 배열의 경우 전체 배열이 반환됩니다.

PHP substr_replace() 구현 예

다음은 언급된 예시입니다.

예시 #1

코드:

<?php
echo substr_replace("Example for ","substring",8);
?>
로그인 후 복사

출력:

PHP substr_replace()

설명: 이 기본 예에서는 substr_replace 함수를 사용하여 첫 번째 문자열 "Example for"를 세 번째 매개변수에 의해 지정된 정확한 위치, 즉 at에서 "substring"으로 바꾸는 것을 볼 수 있습니다. 8번째 위치. 따라서 출력에서 ​​정확히 8번째 위치 이후의 단어 "for"는 "하위 문자열" 단어로 대체됩니다.

예시 #2

코드:

<?php
echo substr_replace("Example for","substring",-3);
?>
로그인 후 복사

출력:

PHP substr_replace()

설명: 이 예에서는 위치 매개변수의 -3 기능을 보여줍니다. 이 빼기 기호는 함수가 뒤에서 시작하는 단어 교체를 시작해야 함을 나타냅니다. 따라서 뒤에서부터 계산을 시작하여 세 번째 위치부터 첫 번째 문자열 대신 두 번째 매개변수를 대체하기 시작합니다.

예시 #3

코드:

<?php
$replace = array("1: Try","2: Try","3: Try two");
echo implode("\n",substr_replace($replace,'Done',3,3));
?>
로그인 후 복사

출력:

PHP substr_replace()

설명: 이 예에서는 배열 내부에 선언된 여러 문자열을 한 번에 바꿉니다. substr_replace 함수를 사용하면 처음 3개 위치에서 "Try"라는 단어를 "Done"이라는 단어로 바꿉니다.

예시 #4

코드:

<?php
echo substr_replace("Example insert", "to ", 8, 0);
?>
로그인 후 복사

출력:

PHP substr_replace()

설명: 이 예에서는 대체 매개변수가 0으로 설정되어 있으므로 substr_replace를 사용하여 삽입을 수행하는 방법을 보여줍니다. 따라서 이 예에서는 삽입만 수행되고 다음이 발생합니다. 출력에 표시된 대로 문자열을 대체하지 않습니다. 두 번째 매개변수 "to"는 지정된 위치, 즉 8번째 위치부터 삽입됩니다.

예시 #5

코드:

<?php
echo substr_replace("dress", "gu", 0, 2);
?>
로그인 후 복사

출력:

PHP substr_replace()

Explanation: In this example, we will specify the length parameter as 2 hence the substr_replace will start replacing the input string starting from the $start parameter which is 0 until 2. Hence from the word “dress”, the first 2 letters will be replaced by “gu” hence becoming “guess”.

Example #6

Code:

<?php
$str = 'Example:/Replace/';
echo "First: $str\n";
// The below 2 displayy the replacement of our input string with 'test'
echo substr_replace($str, 'test', 0) . "\n";
echo substr_replace($str, 'test', 0, strlen($str)) . "\n";
// Here we are inserting the word test at the starting of the string
echo substr_replace($str, 'test', 0, 0) . "\n";
// The below 2 will replace the string "Replace" from input string in $str with 'test'
echo substr_replace($str, 'test', 9, -1) . "\n";
echo substr_replace($str, 'test', -6, -1) . "\n";
// Here we are deleting "Replace" from the input string
echo substr_replace($str, '', 7, -1) . "\n";
?>
로그인 후 복사

Output:

PHP substr_replace()

Explanation: In this example, we are first declaring an input string $str upon which all the operations of the function are going to be performed. In the first part of operation, we are replacing the string completely with the given string as we are specifying both starts as 0. In the second part, we are replacing the “Replace” of the input string with the ‘test’.

Example #7

Code:

<?php
$ip = array('1: PPP', '2: RRR', '3: SSS');
// A basic example where we are replacing all 3 letters of input string with TTT
echo implode('; ', substr_replace($ip, 'TTT', 3, 3))."\n";
// Another case where we are replacing the input string with the different inputs as given below
$replace = array('DDD', 'EEE', 'FFF');
echo implode('; ', substr_replace($ip, $replace, 3, 3))."\n";
// In this case we are replacing all the input characters with 3 different characters
$length = array(1, 2, 3);
echo implode('; ', substr_replace($ip, $replace, 3, $length))."\n";
?>
로그인 후 복사

Output:

PHP substr_replace()

Explanation: In this example, we are showing the use of substr_replace function for replacing multiple strings as shown in input $ip.

Conclusion

Hence this function is used for replacing one string with another string based on the parameters specified. The same can also be used for inserting strings as required when the $start and $length parameter are given in 0 or negative values.

위 내용은 PHP substr_replace()의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
php
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!