Skip to content

Instantly share code, notes, and snippets.

@yuanchuan
Created October 23, 2010 09:10
Show Gist options
  • Save yuanchuan/641977 to your computer and use it in GitHub Desktop.
Save yuanchuan/641977 to your computer and use it in GitHub Desktop.
Generate html tags
<?php
/*
* 快速生成 html 标签
* version: 0.01
* Created: 2010/10/23
*
* TODO: 1.精简函数代码,一般单个函数的长度不超过一屏
* 2.增加容错处理
* 3.<link /> <img /> <br /> 没有考虑进去, 待补充,
* 4.?
*/
function T(){
$result = '';
$args=func_get_args();
$arg_num=func_num_args();
if($arg_num==1){
if(is_string($args[0])){
$result.='<'.$args[0].'></'.$args[0].'>';
}
}else if($arg_num==2){
if(is_string($args[0]) && is_string($args[1])){
$result.='<'.$args[0].'>'.$args[1].'</'.$args[0].'>';
}else if(is_string($args[0]) && is_array($args[1])){
$result.='<'.$args[0];
$mark=true;;
foreach($args[1] as $attr => $value){
if(is_string($attr)){
$result.=' '.$attr.'='.'"'.$value.'"';
}else{
if($mark){$result.='>';$mark=false;}
$result.=$value;
}
}
if($mark){
$result.='></'.$args[0].'>';
}else{
$result.='</'.$args[0].'>';
}
}
}else if($arg_num==3){
if(is_string($args[0]) && is_array($args[1]) && is_string($args[2])){
$result.='<'.$args[0];
foreach($args[1] as $attr => $value){
$result.=' '.$attr.'='.'"'.$value.'"';
}
$result.='>'.$args[2].'</'.$args[0].'>';
}else if(is_string($args[0]) && is_array($args[1]) && is_array($args[2])){
$result.='<'.$args[0];
foreach($args[1] as $attr => $value){
$result.=' '.$attr.'='.'"'.$value.'"';
}
$result.='>';
foreach($args[2] as $value){
$result.=$value;
}
$result.='</'.$args[0].'>';
}
}
return $result;
}
//examples
//-------------------------------------------------------------------------
echo T();
echo T('p');
echo T('p','hi');
echo T('p',array(
'id'=>'test',
'class'=>'test'
),'hi');
echo T('p',array('class'=>'test'),
T('a',array(
'href'=>'http://www.google.com',
'id'=>'goto_google',
'target'=>'_blank'
),'hi google')
);
echo T('div',array(
T('p','content1'),
T('p','content2'),
T('p','content3')
));
echo T('div',array('id'=>'hello'),
T('div',array('id'=>'world'),array(
T('p','hello'),
T('p','world')
)
));
echo T('ul',array('id'=>'nav'),array(
T('li',
T('a',array('href'=>'#','id'=>'current'),'1')),
T('li',
T('a',array('href'=>'#'),'2'))
));
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment