Fetch ID value using preg_match_all in PHP

Asked

Viewed 38 times

1

I get a string in PHP and need to fetch the values of Ids, can be 1, how can be 100 ID’s, how to do? I tried something like this:

$texto = 'Nome1 <span id="indicado-b">Camila</span> Nome2 <span id="indicado-c">Walter</span>';
preg_match_all('/<span id="indicado-(.*)">/',$texto, $match);
print_r($match);

The amount I need to receive is b and c, which are the values of the ID, but it is not returning this, I get:

Array ( [0] => Array ( [0] => Camila Nome2 ) [1] => Array ( [0] => b">Camila Nome2

1 answer

1


You can use the class Domdocument (PHP 5+) and work with the string as HTML, making it easier to manipulate the elements as HTML, and use a loop foreach us spans picking up the attributes id and use preg_match to obtain the letters after the hyphen

<?
$texto = 'Nome1 <span id="indicado-b">Camila</span> Nome2 <span id="indicado-c">Walter</span>';

$d = new DOMDocument();
$d->loadHTML($texto);
$spans = $d->getElementsByTagName("span");

foreach($spans as $id){
   preg_match('/indicado-(.+)/', $id->getAttribute('id'), $match);
   $ids[] = $match[1];
}

var_dump($ids);
?>

At the end you will have an array $ids with the letters you want.

Browser other questions tagged

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