- 积分
- 127886
- 在线时间
- 小时
- 注册时间
- 2010-9-23
- 最后登录
- 1970-1-1
|
- function parse($m){ return call_user_func("parse{$m[1]}",$m[3]);}
- function parsea($str,$attr=array('href')){ return '<a '.parseattr($str,$attr).'>';}
- function parsep($str,$attr=array('align','id')){ return '<p '.parseattr($str,$attr).'>';}
- function parseattr($str,$attr=array()){ if(empty($attr))return ''; $attrs=explode(' ', $str); foreach ($attrs as $k=>$v) { foreach ($attr as $a) { if(strtolower(substr($v, 0,strlen($a)).'=')===strtolower($a.'=')) { continue 2; } } unset($attrs[$k]); } return implode(' ', $attrs);}
- function myreplace($str){ $reg='/<(p|a)(\s+)(.*?[^>])>/is';
- return (preg_replace_callback($reg,'parse',$str));}
- $str='<p align="center" class="asd" id="qwe">adf<a href="#" class="asd" id="qwe" align="center">123</a><div id="iii" style="color:red">4<p id="ww">5</p>6</div></p>';
- echo myreplace(strip_tags($str,'<p><a>'));
- //<p align="center" id="qwe">adf<a href="#">123</a>4<p id="ww">5</p>6</p>
- 重构版:Only for php5.3
- function parseattr($str,$tag,$attr=array())
- {
- if(empty($attr))return '';
- $attrs=explode(' ', $str[2]);
- foreach ($attrs as $k=>$v)
- {
- foreach ($attr as $a)
- {
- if(strtolower(substr($v, 0,strlen($a)).'=')==strtolower($a.'='))
- {
- continue 2;
- }
- }
- unset($attrs[$k]);
- }
- return '< '.$tag.' '.implode(' ', $attrs).'>';
- }
- function myreplace($str,$tag,$attr=array())
- {
- $reg='/< '.$tag.'(\s+)(.*?[^>])>/is';
- return (preg_replace_callback($reg,function ($v) use ($attr,$tag){return parseattr($v,$tag,$attr);},$str));
- }
-
- $str='<p align="center" class="asd" id="qwe">adf<a href="#" class="asd" id="qwe" align="center" rel="nofollow">123<div id="iii" style="color:red">4<p id="ww">56';
- $str=strip_tags($str,'<p><a>');
- $str=myreplace($str,'a',array('href'));
- $str=myreplace($str,'p',array('align','id'));
- echo $str;
复制代码 |
|