The question is:

as from this line: <a title="2" href="link" class="pagenav"></a> get this: <a title="2" href="link" class="pagenav MYCLASS"></a>

In other words, how to add a class to a tag using a regular expression in preg_replace?

PS: if there are other options how to do this, except for preg_replace, I will be very grateful.

    3 answers 3

     $str = '<a title="2" href="link" class="pagenav"></a>'; $pattern = '/<a .*class="pagenav">([^<]*)<\/a>/i'; $replace = '<a title="2" href="link" class="pagenav MYCLASS">$1</a>'; echo preg_replace($pattern, $replace, $str); 

    Although, it would be more correct to use ([^ <] +), but in your example it would not work =)

    • works, thanks for the help! - NastyaChe
     <?php // добавляСмый класс, состоит Ρ‚ΠΎΠ»ΡŒΠΊΠΎ ΠΈΠ· Π±ΡƒΠΊΠ² ΠΈ Ρ†ΠΈΡ„Ρ€ $addclass = 'MYCLASS'; // класс ΠΊ ΠΊΠΎΡ‚ΠΎΡ€ΠΎΠΌΡƒ добавляСм, состоит Ρ‚ΠΎΠ»ΡŒΠΊΠΎ ΠΈΠ· Π±ΡƒΠΊΠ² ΠΈ Ρ†ΠΈΡ„Ρ€ $needcalss = 'pagenav'; // Π½Π΅ΠΏΠ΅Ρ€Π΅Π΄Π°Π²Π°Π΅ΠΌΡ‹ΠΉ Π½Π°Π±ΠΎΡ€ символов понятный для Ρ„ΡƒΠ½ΠΊΡ†ΠΈΠΈ preg_replace $pattern = '%<a [^<>]*class="(?![^"]*?\b' . $addclass . '\b)[^"]*?\b' . $needcalss . '\b\K%i'; $text = '<a title="2" href="link" class="pagenav2">1</a>' . "\n" . '<a title="2" href="link" class="pagenav">2</a>' . "\n" . '<a title="2" href="link" class="pagenav MYCLASS">3</a>'; $text = preg_replace($pattern, ' ' . $addclass, $text); echo $text; 

    Sandbox for tests here .

      As an option:

       $html = '<a title="2" href="link" class="pagenav"></a>'; echo preg_replace('/class="([^"]+)"/i', 'class="$1 MYCLASS"', $html);