我正在完成对CMS的BBCode支持。我使用regex将BBCode转换为html,反之亦然。但是,我在安全方面有点小问题。例如,我有一个正则表达式:
~'[img=(.*?'.(?:jpg|jpeg|png))'|(.*?)'[/img']~s
例如确定这个
[img=somewhere.com'image'08-09-2014'cat.png|This is a cat[/img]
但它也适用于这样的字符串,但我真的不想这样做
[img=somewhere.com" onclick="someBadJSCode()" src="'image'08-09-2014'cat.png|This is a cat[/img]
我认为这次对regex的编辑会有所帮助:
~'[img=([^"]+.*?'.(?:jpg|jpeg|png))'|(.*?)'[/img']~s
但事实并非如此,不知道为什么。有什么想法吗?
多亏了Casimir et Hippolyte,我得到了正则表达式,它适用于url、alt和class部分,没有任何JS危险。
转换此:
[img=somewhere.com/img.jpg|left]cat[/img]
到此:
<img src="somewhere.com/img.jpg" class="left" alt="cat" >
preg_replace方法的模式(1。参数)
~'[img=([^"']+'.(?:jpg|jpeg|png))'|([^"']+)']([^"']+)'[/img']~s
替换preg_replace方法(2。参数)
'<img src="$1" class="'.$this->GetElementClass('img').' $2" alt="$3" >'