在製做模板內容輸出時,很常常會使用<%=%>之類的佔位符,用正則的方式很方便替換這個內容, 工做中只接觸到java、php、js,三種語言的 簡單的實現方式:
java版javascript
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestRex {
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("name", "penngo");
map.put("date", "2013-01-17");
Pattern p = Pattern.compile("<%=(\\w+?)%>");
String str = "<%=date%>, Hello <%=name%>";
Matcher m = p.matcher(str);
StringBuffer sb = new StringBuffer();
boolean result = m.find();
while (result) {
String key = m.group(1);
String value = map.get(key);
m.appendReplacement(sb, value);
result = m.find();
}
m.appendTail(sb);
System.out.println(sb.toString());
}
}php
php版html
<?php
$data = array('name'=>'penngo', 'date'=>'2013-01-17');
function replaceStr( $key, $data){
return $data[ $key];
}
$str = '<%=date%>, Hello <%=name%>';
$str = preg_replace("/<%=(\w+?)%>/ise", "replaceStr('\\1', \$data)", $str);
echo $str;
?>java
js版app
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
var date = {'name':'penngo', 'date':'2013-01-17'};
var str = '<%=date%>, Hello <%=name%>';
str = str.replace(/<%=(\w+?)%>/g, function($0, $1){
var value = date[$1];
return value;
});
document.write(str);
</script>
</head>
<body>
</body>
</html>spa
運行結果輸出:code
2013-01-17, Hello penngohtm
在php使用strip_tags去掉html標籤時,並不能去掉script\style\iframe內部內容ip
<script>內部內容</script> <style>內部內容</style> <iframe>內部內容</iframe>
可使用正則去掉get
$str = preg_replace( "@<script(.*?)</script>@is", "", $str ); $str = preg_replace( "@<iframe(.*?)</iframe>@is", "", $str ); $str = preg_replace( "@<style(.*?)</style>@is", "", $str ); $str = preg_replace( "@<(.*?)>@is", "", $str );