Open In App

How to Replace Part of a string with Another String in PHP?

Last Updated : 17 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

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
<?php

$str = "Welcome to GeeksforGeeks - Computer Science Portal";
$newStr = str_replace("GeeksforGeeks - Computer Science Porta", "GeeksforGeeks", $str);

echo "New String: $newStr";

?>

Output
New String: Welcome to GeeksforGeeksl

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
<?php

$str = "Welcome to GeeksforGeeks - Computer Science Portal";

$newStr = substr_replace($str, "GeeksforGeeks", 11, 50);

echo "New String: $newStr";

?>

Output
New String: Welcome to GeeksforGeeks

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
<?php

$str = "Welcome to GeeksforGeeks - Computer Science Portal";

$newStr = preg_replace("/GeeksforGeeks - Computer Science Portal/", "GeeksforGeeks", $str);

echo "New String: $newStr";

?>

Output
New String: Welcome to GeeksforGeeks

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.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads