phpattrhreflang

Check if attribute hreflang exists


I would like to check if the hreflang attribute exists, I am not sure what the best method is? Is preg_match the only method or is there more?

function add_hreflang() {
    if( !($attribute['hreflang']) ){
        // do something
    }
}
add_action('wp_head', 'add_hreflang', 1);

Solution

  • you can use !empty() check

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

    Edit: To check if any specific attribute is present you can use following code it converts your html element to xml object and then xml to array and find out if the attribute you need exists in the array. link to the orignal html to xml and xml to array code.

    $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']);