----- 019-regex_replace.php -----
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta http-equiv="content-type" content="text/html; charset=utf-8"> 5 <title>Regex-Replace</title> 6 </head> 7 <body> 8 <h1>Regex-Replace</h1> 9 <pre style="font-family:微软雅黑; font-size:13pt"> 10 <?php 11 $str = "喜羊羊灰太狼懒羊羊红太狼"; 12 echo '替换字符串 "<b>喜羊羊灰太狼懒羊羊红太狼</b>"', "\n\n"; 13 14 $result = preg_replace("/...羊羊/", " 樱桃小丸子 ", $str); 15 echo "羊->丸子:", $result, "\n"; 16 17 $result = preg_replace("/...羊羊/", " 樱桃小丸子 ", $str, 1); 18 echo "羊->丸子 一次:", $result, "\n"; 19 20 $result = preg_replace(array("/.{3}羊羊/", "/.{6}狼/"), array("羊", "狼"), $str); 21 echo "羊与狼:", $result, "\n"; 22 23 $result = preg_replace_callback("/.../", "translate", $str, 11); 24 echo "翻译前11个字符:", $result, "\n"; 25 26 27 $str = "熊大熊二"; 28 echo "<b>\n切割字符串</b>\n"; 29 $result = preg_split("/熊/", $str); 30 echo "熊切割后:\n"; 31 var_export($result); 32 $result = preg_split("/熊/", $str, -1, PREG_SPLIT_NO_EMPTY); 33 echo "\n熊切割后忽略空白:\n"; 34 var_export($result); 35 36 echo "<b>\n\n获取正则表达式</b>\n"; 37 $str = "<img src= >!!!"; 38 echo "获取正则表达式"; 39 echo "忽略大小写:", @sql_regcase($str), "\n"; 40 $str = "<img src= >!!"; 41 echo "转义<img src= >!! ", preg_quote('<img src= >!!'), "\n"; 42 echo "转义>img src= >!! ", preg_quote(">img src= >!!"), "\n"; 43 ?> 44 <?php 45 function translate($src) 46 { 47 $maps = array("喜"=>"Happy", "羊"=>"Sheep", "灰"=>"Gray", "太"=>"Too", "狼"=>"Wolf", "懒"=>"Lazy", "红"=>"Red"); 48 return $maps[$src[0]]." "; 49 } 50 ?> 51 </pre> 52 </body> 53 </html>