----- 019-regex_replace.php -----
<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>Regex-Replace</title> </head> <body> <h1>Regex-Replace</h1> <pre style="font-family:微软雅黑; font-size:13pt"> <?php $str = "喜羊羊灰太狼懒羊羊红太狼"; echo '替换字符串 "<b>喜羊羊灰太狼懒羊羊红太狼</b>"', "\n\n"; $result = preg_replace("/...羊羊/", " 樱桃小丸子 ", $str); echo "羊->丸子:", $result, "\n"; $result = preg_replace("/...羊羊/", " 樱桃小丸子 ", $str, 1); echo "羊->丸子 一次:", $result, "\n"; $result = preg_replace(array("/.{3}羊羊/", "/.{6}狼/"), array("羊", "狼"), $str); echo "羊与狼:", $result, "\n"; $result = preg_replace_callback("/.../", "translate", $str, 11); echo "翻译前11个字符:", $result, "\n"; $str = "熊大熊二"; echo "<b>\n切割字符串</b>\n"; $result = preg_split("/熊/", $str); echo "熊切割后:\n"; var_export($result); $result = preg_split("/熊/", $str, -1, PREG_SPLIT_NO_EMPTY); echo "\n熊切割后忽略空白:\n"; var_export($result); echo "<b>\n\n获取正则表达式</b>\n"; $str = "<img src= >!!!"; echo "获取正则表达式"; echo "忽略大小写:", @sql_regcase($str), "\n"; $str = "<img src= >!!"; echo "转义<img src= >!! ", preg_quote('<img src= >!!'), "\n"; echo "转义>img src= >!! ", preg_quote(">img src= >!!"), "\n"; ?> <?php function translate($src) { $maps = array("喜"=>"Happy", "羊"=>"Sheep", "灰"=>"Gray", "太"=>"Too", "狼"=>"Wolf", "懒"=>"Lazy", "红"=>"Red"); return $maps[$src[0]]." "; } ?> </pre> </body> </html>