Home > Software design >  Using Regex preg_replace <h2> to <h2 with ID
Using Regex preg_replace <h2> to <h2 with ID

Time:08-24

I have a for loop which i want to add ID to my <h2> and <h3> using preg_replace, my problem is I cant get the tag which has a class (like this <h2 >test</h2>). PS: the text between tags is important and I pass it with the $r[$i] variable.

for ($i = 0; $i < count($r); $i  ) {
    $replace_quary = "<h2 id='t" . $i . "'>" . $r[$i] . "</h2>";
    $content = preg_replace('#<h2.*?>('. $r[$i] .')</h2>#i', $replace_quary, $content);
    echo $content;
}

CodePudding user response:

Use a capture group to copy the part of the tag that matches .*?.

Also use preg_quote() to escape any special characters in $r[$i].

for ($i = 0; $i < count($r); $i  ) {
    $text = preg_quote($r[$i]);
    $replace_quary = "<h2 id='t$i' $1>$2</h2>";
    $content = preg_replace('#<h2(.*?)>('. $text .')</h2>#i', $replace_quary, $content);
    echo $content;
}

DEMO

  • Related