我想检查hreflang属性是否存在,我不确定最好的方法是什么?是preg_match
还是唯一的方法?
function add_hreflang() {
if( !($attribute['hreflang']) ){
// do something
}
}
add_action('wp_head', 'add_hreflang', 1);
您可以使用!empty()
检查
function add_hreflang() {
if( !empty($attribute['hreflang']) ){
// do something
}
}
编辑:要检查是否存在任何特定的属性,您可以使用以下代码将其html元素转换为xml对象,然后将xml转换为array,并找出所需的属性是否存在于数组中。链接到原始的html to xml和xml to array代码。
$str = '<a href="http://example.com" anotherAttrib="someValue">Link</a>';
$link = new SimpleXMLElement($str);
// print_r($link);
function xml2array( $xmlObject, $out = array () ){
foreach ( (array) $xmlObject as $index => $node )
$out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;
return $out;
}
$arr = xml2array($link);
print_r($arr['@attributes']);