PHP tutorial-String Manipulation: find and replace |
||||||||||||||
String manipulation in PHPfind and replace functionsThe strpos(String, String_to_find) function returns the position of the String_to_find in the String. The str_replace(Old_string,New_string,String) function is used to replace the Old_string with the New_string. In the example below, we create a simple find-and-replace word program that allows a user to find and replace words in a textarea box. Example: <html> <head> <title>Find and Replace<title> <?php $str1=$_GET['txtmessage']; global $strnew; $str_to_find=$_GET['txtfind']; $str_to_replace=$_GET['txtreplace']; $pos=strpos($str1,$str_to_find);//find the word to replace if($pos>=0)//The word is found. Then make replacement. $strnew=str_replace($str_to_find,$str_to_replace,$str1); ?> </head> <body> <form action="welcome.php" method="get"> <table> <tr> <?php
//assign the new string to the textarea |
| |||||||||||||
|
||||||||||||||