How to Replace Part of a string with Another String in PHP?
Given a String, the task is to replace the part of a string with another string in PHP. There are several methods to replace part of a string with another string. This operation is useful when you need to modify a string, such as replacing certain characters or substrings.
Table of Content
- Using str_replace() Function
- Using substr_replace() Function
- Using Regular Expressions
Approach 1: Using str_replace() Function
The str_replace() function is a built-in PHP function that replaces all occurrences of a search string with a replacement string in a given string.
<?php
$str = "Welcome to w3wiki - Computer Science Portal";
$newStr = str_replace("w3wiki - Computer Science Porta", "w3wiki", $str);
echo "New String: $newStr";
?>
Output
New String: Welcome to w3wikil
Explanation:
- The str_replace() function takes three arguments: the search string, the replacement string, and the input string. It replaces all occurrences of the search string with the replacement string in the input string.
Approach 2: Using substr_replace() Function
The substr_replace() function replaces a portion of a string with another string.
<?php
$str = "Welcome to w3wiki - Computer Science Portal";
$newStr = substr_replace($str, "w3wiki", 11, 50);
echo "New String: $newStr";
?>
Output
New String: Welcome to w3wiki
Explanation:
The substr_replace() function takes four arguments: the input string, the replacement string, the start position of the replacement, and the length of the portion to be replaced.
Approach 3: Using Regular Expressions
Regular expressions can also be used to replace part of a string with another string.
<?php
$str = "Welcome to w3wiki - Computer Science Portal";
$newStr = preg_replace("/w3wiki - Computer Science Portal/", "w3wiki", $str);
echo "New String: $newStr";
?>
Output
New String: Welcome to w3wiki
Explanation:
The preg_replace() function performs a regular expression search and replace. It takes three arguments: the regular expression pattern, the replacement string, and the input string.
Contact Us