一 实例
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <title>应用str_replace()函数替换子字符串</title> <style type="text/css"> <!-- .STYLE3 { font-size: 12px; color: #FC8002; } .STYLE4 {font-size: 13px} --> </style> </head> <body> <?php $str=" 予人温暖,自己也更温暖。予人快乐,自己也将更快乐。这是一种境界,也是心灵上的一种拥有。在温暖里,人才不会迷失,在相互扶持中,婚姻才会更长久。就算偶有寒流来袭,只要两颗心相互取暖,又怎么会给寂寞留下可乘之机呢。"; if($_POST["Submit"]=="提交"){ $str2=$_POST[str2]; $str1="<font color='#FF0000'>$_POST[str1]</font>"; $stres = str_replace($str2,$str1,$str); } ?> <table width="760" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="415" height="490" align="center" valign="top" background="images/bg.jpg"><table width="400" height="462" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="161" height="165"> </td> <td width="239"> </td> </tr> <tr> <td height="112" colspan="2" align="center"><table width="360" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="360" align="left"><span class="STYLE4">原字符串:<br> <?php echo $str;?></span></td> </tr> </table></td> </tr> <form name="form1" method="post" action="index.php"> <tr> <td height="32" align="right"><span class="STYLE3">被替换的字符</span></td> <td align="left"><input name="str2" type="text" id="str2" size="24"></td> </tr> <tr> <td height="30" align="right"><span class="STYLE3">替换的字符</span></td> <td height="30"><input name="str1" type="text" id="str1" size="24"></td> </tr> <tr> <td> </td> <td align="center" valign="top"><input name="Submit" type="submit" id="Submit" value="提交"> </td> </tr> </form> </table></td> <td width="345" align="center" valign="middle" background="images/bg1.jpg"><table width="300" border="0" cellspacing="0" cellpadding="0"> <tr> <td class="STYLE4"><?php echo $stres; ?></td> </tr> </table> </td> </tr> </table> </body> </html>
二 运行结果
三 说明
mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )
该函数返回一个字符串或者数组。该字符串或数组是将 subject 中全部的 search 都被 replace 替换之后的结果。
如果没有一些特殊的替换需求(比如正则表达式),你应该使用该函数替换 ereg_replace() 和 preg_replace()。
参数
如果 search 和 replace 为数组,那么 str_replace() 将对 subject 做二者的映射替换。如果 replace 的值的个数少于 search 的个数,多余的替换将使用空字符串来进行。如果 search 是一个数组而 replace 是一个字符串,那么 search 中每个元素的替换将始终使用这个字符串。该转换不会改变大小写。
如果 search 和 replace 都是数组,它们的值将会被依次处理。
search
查找的目标值,也就是 needle。一个数组可以指定多个目标。
replace
search 的替换值。一个数组可以被用来指定多重替换。
subject
执行替换的数组或者字符串。也就是 haystack。
如果 subject 是一个数组,替换操作将遍历整个 subject,返回值也将是一个数组。
count
如果被指定,它的值将被设置为替换发生的次数。
返回值
该函数返回替换后的数组或者字符串。