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

Sunday, November 20, 2022

[FIXED] How to remove indentations or spaces from HTML comment tags?

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

Issue

Here is my code:

$template = preg_replace("\s*/\<\!\-\-\{(.+?)\}\-\-\>/s", "{\\1}", $template);

And the html which I want to remove indentations of comment:

    <!--{hello}-->
    <div class="novalue">
        <a>URL</a>
    </div>
    <!--{/hello}-->

I want it to be like this:

{hello}
    <div class="novalue">
        <a>URL</a>
    </div>
{/hello}

But, the result was:

{hello}
        <div class="novalue">
            <a></a>
        </div>{/hello}

My question is, why can't it just remove other space at the front of the current line ?


Solution

\s includes linebreak, you want to use \h for horizontal spaces instead And don't escape all characters in your regex, it becomes unreadable:

$html = <<<EOD
    <!--{hello}-->
    <div class="novalue">
        <a>URL</a>
    </div>
    <!--{/hello}-->
EOD;

echo preg_replace('#\h*<!--({.+?})-->#', '$1', $html);

Output:

{hello}
    <div class="novalue">
        <a>URL</a>
    </div>
{/hello}

Explanation:

#           # regex delimiter
  \h*       # 0 or more horizontal spaces
  <!--      # literally, begin comment
  (         # start group 1
    {       # opening curly brace
    .+?     # 1 or more any character, not greedy
    }       # closing curly brace
  )         # end group 1
  -->       # literally, end comment
#           # regex delimiter


Answered By - Toto
Answer Checked By - Terry (PHPFixing Volunteer)
  • 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