PHP正则表达式从标记过滤属性

时间:2016-03-31 19:16:12

标签: php jquery regex

我使用PHP脚本将一些自定义标签转换为有效的Bootstrap标签,因为我需要将它们放在许多脚本中,并且只需要一个地方来管理设置。

转换例如<well><div class="well">很简单,但如果我想将<well title="hello">转换为<div class="well"><h4>hello</h4>,我应该采用什么模式?

所以我需要能够识别具有任何值的属性的标记,但我还需要具有该值。一旦事情变得复杂一点,正则表达式对我来说仍然是一个谜......

谢谢!

1 个答案:

答案 0 :(得分:0)

它不是很有活力,但适用于这个具体的例子......它是你需要的吗?

$re = "/\\<([\\w]+) ?(([\\w]+)\\=\\\"([\\w]+)\\\")\\>/"; 
$str = "<well title=\"hello\">";
preg_match($re, $str, $matches);
print_r($matches);
$new_tag = '<div class="'.$matches['1'].'"><h4>'.$matches[4].'</h4></div>';
echo "\n".$new_tag;