2011-12-01 52 views
-3

我遇到了以下问题。preg_match排除

我需要在将HTML呈现给浏览器之前清理HTML。

到目前为止,当前的正则表达式匹配像“{varname}”一样没有问题,但是我需要排除在脚本标签中找到的匹配。

* 例子是有点不清楚,所以更新* 例子:

<html> 
<head></head> 
<body> 
this is an example `{var}` variable, <- this should be matched/removed 
    <script> 
    // don't match below arguments in other words don't let regex remove them/match them 
    myMethod("{param1:'foo', param2:'bar'}"); 
    </script> 
</body> 
</html> 
+2

我不确定你在这里问什么,但它听起来像你用正则表达式解析HTML。 [不要那样](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags#1732454)。使用HTML解析器。 –

+0

你想做什么?我在这里有点困惑。 –

+0

嗨Macek,我没有用正则表达式解析html,我正在清理。为了您的信息,数据由CodeIgniter的解析器设置,(CI使用{}作为params/vars)但是我不想{ }在我的输出到浏览器(这发生在未定义变量时)。所以这就是为什么我要清理,但是我想保留在javascript ofcourse中括号。 – user1076168

回答

1

使之具体化,只是匹配字母数字字符:

preg_replace("~\{(\w+)}~i", "", $sContent); 

将避免{x: 'y'}例子问题了。


要使用preg排除文档零件,请使用preg_replace_callback;列出不需要的(<script>.+?</script>)|...作为第一选择,然后在回调中切换句柄。

+0

tnxx ..我是如此愚蠢专注于排除脚本问题,我错过了一些简单的匹配只字母数字.. Tnxx! – user1076168