检查属性 hreflang 是否存在

Check if attribute hreflang exists

我想检查 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 转换为数组并找出您需要的属性是否存在于数组中. link 到原始 html to xml and 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']);