📜  php substr_replace - PHP (1)

📅  最后修改于: 2023-12-03 15:18:21.271000             🧑  作者: Mango

PHP substr_replace

Introduction

substr_replace is a built-in function in PHP that allows a programmer to replace a part of a string with another substring. The function takes three required arguments: the original string, the replacement string, and the position of the start of the substring to replace.

Syntax

The syntax of the substr_replace function is as follows:

substr_replace(string $original_string , string $replacement_string , int $start [, int $length = 0])

The function returns the modified string.

Arguments
  • $original_string: The original string that needs to be modified.

  • $replacement_string: The string that will replace the substring starting from the $start position.

  • $start: The position at which to start replacing the substring.

  • $length (optional): The length of the substring that needs to be replaced. If $length is not specified, it will replace all the characters after the $start position until the end of the string.

Example

The following example shows how to use the substr_replace function to replace a substring in a string:

$string = "Hello World";
$new_string = substr_replace($string, "PHP", 6, 5);
echo $new_string;

Output:

Hello PHP

In this example, the substr_replace function replaces the substring "World" starting from the 6th position with "PHP".

Conclusion

The substr_replace function is a useful built-in function in PHP for manipulating strings. It allows programmers to replace a substring with another string. By providing the start and length of the substring to replace, programmers can easily modify strings as needed.