Home > Backend Development > PHP Tutorial > 谁帮忙写一下这个正则

谁帮忙写一下这个正则

WBOY
Release: 2016-06-23 14:09:59
Original
795 people have browsed it


例如

 

我要匹配出来一个HTML标签的class 或者 id 是什么。。(有ID拿ID,没有就拿CLASS)
最好也能匹配出来到底是div还是span还是其它


回复讨论(解决方案)

提供一个jQuery的解决方式
<script> <br /> function getTagInfo(e){ <br /> var str=''; <br /> if(jQuery(e).attr('id')){ <br /> str += 'id:'+jQuery(e).attr('id'); <br /> }else if(jQuery(e).attr('class')){ <br /> str += 'class:'+jQuery(e).attr('class'); <br /> <br /> }else{ <br /> str += '既没设置id也没设置class属性'; <br /> } <br /> str += '\ntagName:'+jQuery(e).get(0).tagName; <br /> alert(str); <br /> } <br /> </script>

点我试试

点我试试

刚刚没注意将其写入到源代码中,使得格式错乱,看如下:

function getTagInfo(e){	var str='';	if(jQuery(e).attr('id')){		str += 'id:'+jQuery(e).attr('id');	}else if(jQuery(e).attr('class')){		str += 'class:'+jQuery(e).attr('class');			}else{		str += '既没设置id也没设置class属性';	}	str += '\ntagName:'+jQuery(e).get(0).tagName;	alert(str);}
Copy after login

<div id='myDivId' class="myDivClass" onclick="getTagInfo(this)">点我</div><span id='mySpanId' class="mySpanClass" onclick="getTagInfo(this)">点我</span>
Copy after login

$html = '<div id="myid" class="myclass"></div>';$dom = new DOMDocument();@$dom->loadHTML($html);$x = new DOMXPath($dom); foreach($x->query("//div") as $node)//如果要span的话,//div 换成 //span {    echo $node->getAttribute("id");	echo '<br />';	echo $node->getAttribute("class");}
Copy after login

我也没看清楚,原来span或者div是不一定的,那就换 //* 然后 nodeName 获取HTML标签名。

<?php$html = '<div id="myid" class="myclass"></div>';$dom = new DOMDocument();@$dom->loadHTML($html);$x = new DOMXPath($dom); foreach($x->query("//*") as $node) {    echo $node->getAttribute("id"); //myid	echo '<br />';	echo $node->getAttribute("class"); //myclass	echo '<br />';	echo $node->nodeName; // div} ?>
Copy after login

[/code]

用PHPQUERY 可以实现吗



[/code]

用PHPQUERY 可以实现吗
sorry!PHPQUERY我没接触过

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template