【发布时间】:2011-09-21 12:27:16
【问题描述】:
我正在尝试使用 preg_replace 替换
<a href="WWW.ANYURL.COM">DISPLAY_TEXT</a>
与
<a href="WWW.ANYURL.COM">DISPLAY_TEXT</a>
这是我的代码:
$string = htmlentities(mysql_real_escape_string($string1));
$newString = preg_replace('#<a\ href="([^&]*)">([^&]*)</a>#','<a href="$1">$2</a>',$string);
如果我进行有限的测试,例如:
$newString = preg_replace('#<a\ href#','TEST',$string);
然后
<a href="WWW.ANYURL.COM">DISPLAYTEXT</a>
变成
TEST="WWW.ANYURL.COM">DISPLAYTEXT</a>
但如果我试图让它也匹配“=”它就像找不到匹配一样,即
$newString = preg_replace('#<a\ href=#','TEST',$string);
原样返回:
<a href="WWW.ANYURL.COM">DISPLAY_TEXT</a>
我已经做了几个小时,任何帮助将不胜感激。
编辑:上下文中的代码
$title = clean_input($_POST['title']);
$story = clean_input($_POST['story']);
function clean_input($string)
{
if(get_magic_quotes_gpc())
{
$string = stripslashes($string);
}
$string = htmlentities(mysql_real_escape_string($string));
$findValues = array("<b>","</b>");
$newValues = array("<b>", "</b>");
$newString = str_replace($findValues, $newValues, $string);
$newString2 = preg_replace('#<a\ href="([^&]*)">([^&]*)</a>#','<a href="$1">$2</a>',$newString);
return $newString2;
}
示例 $story = Lorem ipsum dolor sit amet,consectetur adipiscing elit。 <a href="www.google.com">Google</a> Vivamus quis sem felis。 Morbi vitae neque ac neque blandit malesuada lobortis 坐在 amet justo。 Donec convallis, nibh ut lacinia tempor, neque felis scelerisque nibh, at feugiat lectus erat in nulla。在等 euismod nunc。 <pernicious code></code>Pellentesque vitae ante orci, vitae ultrices neque。 <a href="www.yahoo.com">Yahoo</a> 在 non nulla sapien,前庭 faucibus metus。 Fusce egestas viverra arcu, <b>ac</b> sagittis leo facilisis in. Nulla facilisi。
我希望只允许像 href 和粗体这样的几个标签作为代码通过。
【问题讨论】:
-
呃...嗯..还有其他人看到这个问题的逻辑问题吗?
-
等等——你想做什么?如果您只想撤消
htmlentities的工作,为什么还要使用htmlentities? -
大多数人会使用
html_entity_decode(),然后继续处理更重要的事情...... -
我不知道你想要达到什么,但也许
strip_tags($str, '<a>')给你一个正确的结果而不是htmlentities() -
我只想撤消某些标签上的工作。我正在尝试清理要添加到数据库的字符串,但允许某些安全的 html 标记。
标签: php html regex preg-replace