Capture all ID with preg_match

Asked

Viewed 90 times

0

I have two div

<div id"opcao1"></div>

<div id"opcao1a"></div>

I am 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 option div 1, the option div 1, does not return.

Someone knows how to do this

  • It wouldn’t be easier for you to get this ID with jQuery or JS?

  • Have two Ivs where? Where did you get this function? How are you using the function? In fact, why use a function that does almost the same thing as the preg_match, but returns only one item? It would be nice [Dit] the question and put more details, because the way it is, the context is very dependent on the imagination of each one. Explaining better increases the chance of getting a solution. Although I think simply eliminating the redundant function get ID already solves the problem.

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 code of the question there is a syntax error. The attribute is missing = in the tags div.

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.