How to replace a symbol in a text string in php?

by cortez.connelly , in category: PHP General , 6 months ago

How to replace a symbol in a text string in php?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by jerad , 6 months ago

@cortez.connelly 

In PHP, you can replace symbols in a text string using the str_replace() function. This function searches for a specified symbol or string of symbols within a given text string and replaces them with a new symbol.


Here is an example of how to use str_replace() to replace a symbol in a text string:

1
2
3
$text = "Hello world!";
$newText = str_replace("!", "?", $text);
echo $newText;


In the above example, we replace the exclamation mark symbol (!) in the $text string with a question mark symbol (?). The resulting $newText string will be "Hello world?".


You can also use str_replace() to replace multiple symbols at once by providing arrays as the search and replacement parameters. Here is an example:

1
2
3
4
5
$text = "Hello, <<name>>!";
$search = array("<<name>>", "!");
$replacement = array("John", "?");
$newText = str_replace($search, $replacement, $text);
echo $newText;


In this case, the $search array contains the symbols "<>" and "!". The $replacement array contains the texts "John" and "?". The function will search for both symbols in the text string and replace them accordingly. The resulting $newText string will be "Hello, John?".


Remember that the str_replace() function is case-sensitive. If you want to perform a case-insensitive replacement, you can use the str_ireplace() function instead.

Member

by aubrey , 6 months ago

@cortez.connelly 

$text = "Hello world!"; $newText = str_replace("!", "?", $text); echo $newText;


$text = "Hello, <>!"; $search = array("<>", "!"); $replacement = array("John", "?"); $newText = str_replace($search, $replacement, $text); echo $newText;