Capture entire ID with preg_match

0

I have two div

<div id"opcao1"></div>

<div id"opcao1a"></div>

I'm using this function to capture the id

function obterID($string) {
    $res = preg_match('~id="([\w]+)"~i', $string, $IDs);
    if ($res){
        return $IDs[1];
    } else {
        return "";
    }      
}

But I only get the div1 option, the div1 option, does not return.

Does anyone know how to do this?

    
asked by anonymous 29.02.2016 / 19:53

1 answer

3
$str = '
<div id="opcao1"></div>

<div id="opcao1a"></div>
';

$doc = new DOMDocument();

@$doc->loadHTML($str); // Aqui usamos o inibidor de erros '@' para evitar o disparo de erros devido a semântica inválida de algum código html.

$tags = $doc->getElementsByTagName('div');

foreach ($tags as $tag) {
    echo $tag->getAttribute('id').PHP_EOL.'<br />';
}

obs: In the original question code there is a syntax error. The = attribute is missing in the div tags.

Wrong: <div id"opcao1"></div> .

Correction: <div id="opcao1"></div> .

    
01.03.2016 / 08:58