PHP offers multiple functions for extracting and replacing parts of strings. Below are some frequently used functions and how to use them.
The substr() function extracts a specified portion of a string and returns it as a substring. The basic syntax is:
substr(string $string, int $start, int $length = null)
Here, $start is the starting position of the substring, and $length is the length of the substring. If $length is omitted, the substring extends to the end of the string.
Example:
$string = "Hello World!"; $substring = substr($string, 0, 5); // Returns "Hello"
The substring() function behaves similarly to substr(), but extracts a substring from the end of the string towards the start. Its basic syntax is:
substring(string $string, int $start, int $length = null)
Parameters have similar meanings as in substr().
Example:
$string = "Hello World!"; $substring = substring($string, 10, 5); // Returns "World"
The substr_replace() function replaces part of a string with another string. Syntax:
substr_replace(string $string, string $replacement, int $start, int $length = null)
$start specifies where replacement starts, and $length specifies the length to be replaced.
Example:
$string = "Hello World!"; $substring = substr_replace($string, "there", 7, 5); // Returns "Hello there!"
The str_replace() function replaces all occurrences of a specified substring with another string. Syntax:
str_replace(mixed $search, mixed $replace, mixed $subject)
$search is the value to be replaced, $replace is the replacement string, and $subject is the target string.
Example:
$string = "Hello World!"; $substring = str_replace("World", "there", $string); // Returns "Hello there!"
The functions described above are the most commonly used tools in PHP for substring extraction and replacement. Proper use of these functions can improve the efficiency of string manipulation and enhance code readability.