How to Add Attribute to HTML Tag using PHP

In some cases, you need to add attribute to HTML tag dynamically. Regular Expressions (Regex) makes it easy to replace or add attributes to HTML tags in PHP. You can easily add attribute to HTML tags using Regex and PHP.

The preg_replace() function searches string matches to the pattern (regular expression) and replaces with replacement. Use preg_replace() function with regular expression to add attribute to HTML tag using PHP.

The following example code will add style attribute to HTML <a> tag.

<?php
$html 
'<a href="https://www.codexworld.com" class="cw-link" title="CodexWorld">Visit CodexWorld</a>';
$result preg_replace('/(<a\b[^><]*)>/i''$1 style="xxxx:yyyy;">'$html);

Output:

<a href="https://www.codexworld.com" class="cw-link" title="CodexWorld" style="xxxx:yyyy;">Visit CodexWorld</a>

You can add any attributes to HTML tags using preg_replace() function in PHP.

1 Comment

  1. Niels Said...

Leave a reply

keyboard_double_arrow_up