Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
PHP program to replace a word with a different symbol in a sentence
To replace a word with a different symbol in a sentence, PHP provides the str_replace() function. This function searches for specified words and replaces them with new values.
Syntax
str_replace(search, replace, subject, count)
Parameters
The str_replace() function accepts the following parameters ?
- search − The value to search for (can be string or array)
- replace − The replacement value (can be string or array)
- subject − The string or array to search in
- count − Optional variable to store the number of replacements
Example
<?php
$my_str = "This is a sample only";
$search_str = array("sample", "This");
$replace_str = array("simple", "That");
$result = str_replace($search_str, $replace_str, $my_str);
print_r("The final replaced string is: ");
print_r($result);
?>
The final replaced string is: That is a simple only
How It Works
In the example above ?
- The original string is defined:
"This is a sample only" - Search array contains words to find:
["sample", "This"] - Replace array contains replacement words:
["simple", "That"] - The function replaces "sample" with "simple" and "This" with "That"
Single Word Replacement
For replacing a single word, you can use strings instead of arrays ?
<?php
$sentence = "PHP is difficult to learn";
$new_sentence = str_replace("difficult", "easy", $sentence);
echo $new_sentence;
?>
PHP is easy to learn
Conclusion
The str_replace() function is an efficient way to replace words or symbols in PHP strings. It supports both single replacements and multiple replacements using arrays.
Advertisements
