Backend Development 4 min read

Using PHP str_replace() Function: Syntax, Examples, and Applications

This article explains the PHP str_replace() function, its syntax, parameter details, and provides multiple code examples demonstrating simple string replacement, array-based replacements, URL modification, and HTML tag transformation.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP str_replace() Function: Syntax, Examples, and Applications

PHP is a popular server‑side scripting language often used for web development, and the str_replace() function is a built‑in tool for replacing substrings within a string.

Syntax of str_replace()

<code>str_replace($search, $replace, $subject)</code>

The three parameters are:

$search : the substring(s) to be replaced (string or array).

$replace : the replacement substring(s) (string or array).

$subject : the original string or array to search in.

Usage Example

A simple example that replaces the word "world" with "PHP":

<code>$oldstr = "Hello, world!";
$newstr = str_replace("world", "PHP", $oldstr);
echo $newstr;</code>

Output:

<code>Hello, PHP!</code>

Beyond single words, str_replace() can replace punctuation, numbers, or multiple substrings using arrays. The following example replaces commas and the name "John" with a semicolon and "Peter":

<code>$oldstr = "Hello, my name is John.";
$search = array(",", "John");
$replace = array(";", "Peter");
$newstr = str_replace($search, $replace, $oldstr);
echo $newstr;</code>

Output:

<code>Hello; my name is Peter.</code>

If you need to replace every occurrence matching a pattern, you can use preg_replace() instead.

str_replace() can also be used for URL and HTML tag manipulation. Example of changing a domain in a URL:

<code>$url = "http://www.example.com/index.php?id=1";
$newurl = str_replace("example.com", "mywebsite.com", $url);
echo $newurl;</code>

Output:

<code>http://www.mywebsite.com/index.php?id=1</code>

Similarly, HTML tags can be replaced to improve semantics:

<code>$html = "<p><b>Hello</b>, <i>world</i>!</p>";
$newhtml = str_replace(
    array("<b>", "</b>", "<i>", "</i>"),
    array("<strong>", "</strong>", "<em>", "</em>"),
    $html
);
echo $newhtml;</code>

Output:

<code><p><strong>Hello</strong>, <em>world</em>!</p></code>

The str_replace() function is a versatile tool for any PHP developer needing to modify strings, URLs, or HTML content during web development.

PHPcode examplesstring replacementstr_replace
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.