PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 20, 2022

[FIXED] How to use preg_replace to inject a classname into an html node?

 November 20, 2022     html, inject, php, preg-replace, regex     No comments   

Issue

I set myself this rather simple sounding challenge but now I am stuck trying to figure out how to inject a classname onto the <body> dom element of my document.

The complexity is because I don't have control over the HTML markup I am getting via the file_get_contents function (a third party feeds the files via FTP).

So the body element could be a multitude of different ways, for example:

<body>
<body id="my-id" data-attribute="content">
<body data-attribute="content">
<body class="already-existing-class" id="my-id" data-attribute="content">

and so on… not even the order of said attributes is under my control so you may have a class= before the id= et cetera.

I think you all understand the complexity I am talking about here; (I hope).

What I basically need is a way to use preg_replace() to inject a new class into either an existing class attribute on the body (if one already exists) or add the class attribute itself with my new class in it.

Any help would be much appreciated.

If this has already been answered, please feel free to point it out. I tried searching but with such generic terms it was hard to find what I was looking for.

Thanks for reading.

J.


Solution

A regex can be extremely cumbersome for this application. Instead, I suggest you use an HTML parser, such as PHP's DOMDocument. Here is an example.

$node1 = '<body>';
$node2 = '<body id="my-id" data-attribute="content">';
$node3 = '<body data-attribute="content">';
$node4 = '<body class="already-existing-class" id="my-id" data-attribute="content">';

foreach( range( 1, 4) as $i)
{
    $var = 'node'.$i;
    $doc = new DOMDocument();
    $doc->loadHTML( $$var);
    foreach( $doc->getElementsByTagName( 'body') as $tag)
    {
        $tag->setAttribute('class', ($tag->hasAttribute('class') ? $tag->getAttribute('class') . ' ' : '') . 'some-new-class');
    }
    echo htmlentities( $doc->saveHTML()) . "\n";
}

Demo

Notice the output of the <body> tag is correct. You (or another SO member) are free to determine how to extract just the body tag from the DOMDocument.



Answered By - nickb
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing