检查属性hreflang是否存在

问题描述 投票:0回答:1

我想检查hreflang属性是否存在,我不确定最好的方法是什么?是preg_match还是唯一的方法?

function add_hreflang() {
    if( !($attribute['hreflang']) ){
        // do something
    }
}
add_action('wp_head', 'add_hreflang', 1);
php attr hreflang
1个回答
0
投票

您可以使用!empty()检查

function add_hreflang() {
  if( !empty($attribute['hreflang']) ){
    // do something
  }
}

编辑:要检查是否存在任何特定的属性,您可以使用以下代码将其html元素转换为xml对象,然后将xml转换为array,并找出所需的属性是否存在于数组中。链接到原始的html to xmlxml 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']);
© www.soinside.com 2019 - 2024. All rights reserved.