Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 5843289
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T12:08:02+00:00 2026-05-22T12:08:02+00:00

How would you add a class named newClass to an opening tag like <a

  • 0

How would you add a class named newClass to an opening tag like <a class='abc'> or <p style=display:block> using php?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-22T12:08:03+00:00Added an answer on May 22, 2026 at 12:08 pm

    Regexp example:

    <?php
    function addClass($htmlString = '', $newClass) {
        $pattern = '/class="([^"]*)"/';
    
        // class attribute set
        if (preg_match($pattern, $htmlString, $matches)) {
            $definedClasses = explode(' ', $matches[1]);
            if (!in_array($newClass, $definedClasses)) {
                $definedClasses[] = $newClass;
                $htmlString = str_replace($matches[0], sprintf('class="%s"', implode(' ', $definedClasses)), $htmlString);
            }
        }
    
        // class attribute not set
        else {
            $htmlString = preg_replace('/(\<.+\s)/', sprintf('$1class="%s" ', $newClass), $htmlString);
        }
    
        return $htmlString;
    }
    
    echo addClass('<a class="abc">', 'newClass');
    echo addClass('<p style=display:block>', 'newClass');
    

    using http://php.net/manual/en/book.dom.php example

    <?php
    function addClass($node = null, $className) {
        $result = false;
    
        if (is_string($node)) {
            $dom = DOMDocument::loadXml($node);
            if ($dom instanceof DOMDocument) {
                $definedClasses = explode(' ', $dom->documentElement->getAttribute('class'));
                if (!in_array($className, $definedClasses)) {
                    $dom->documentElement->setAttribute(
                        'class', $dom->documentElement->getAttribute('class') . ' ' . $className
                    );
                }
    
                $result = $dom->saveXml($dom->documentElement, true);
            }
        }
        elseif ($node instanceof DOMElement) {
            // this code repetition, could of course be avoided using some more sophisticated structures 
            $definedClasses = explode(' ', $node->getAttribute('class'));
            if (!in_array($className, $definedClasses)) {
                $node->setAttribute('class', $node->getAttribute('class') . ' ' . $className);
            }
    
            $result = $node;
        }
    
        return $result;
    }
    
    // using a string as input
    echo addClass('<a class="abc"></a>', 'newClass');
    
    // using a DOMElement as input
    $dom = DOMDocument::loadHtml('<div><a id="something"></a></div>');
    $xpath = new DOMXPath($dom);
    
    $node = $xpath->query('//*[@id="something"]')->item(0);
    if ($node instanceof DOMElement) {
        addClass($node, 'newClass');
        echo $dom->saveXml($node, true);
    }
    

    I’m purposely not using loadHTML (inside the function) to prevent having to dive down into the autogenerated html structure to find the actual given $htmlString. This of course implies that $htmlString has to be well-formed.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I would like to add an operator to a class. I currently have a
How can I extend a builtin class in python? I would like to add
I would like to add a Help screen to my app using the options
I have an entity in EF named Profile and I would like to add
Would it be possible to add a new operator to the String class that
I'd like to write a gmail extension that would add a button on the
I'm using Elmah with ASP.NET and wondering how I would add custom data, such
I don't understand how using a 'challenge token' would add any sort of prevention:
I have a game here, and I would like to add event handlers to
I would like my application to write out different trace files named like MachineName_UserName_yyyymmdd_hhmmss.txt

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.