如何从 HTML 注释标签中删除缩进或空格?

这是我的代码:


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

而且html我要删除评论的缺口:


    <!--{hello}-->

    <div class="novalue">

        <a>URL</a>

    </div>

    <!--{/hello}-->

我希望它是这样的:


{hello}

    <div class="novalue">

        <a>URL</a>

    </div>

{/hello}

但是,结果是:


{hello}

        <div class="novalue">

            <a></a>

        </div>{/hello}

我的问题是,为什么不能删除当前行前面的其他空格?



临摹微笑
浏览 181回答 3
3回答

梵蒂冈之花

\s包括换行符,您想\h用于水平空格并且不要转义正则表达式中的所有字符,它变得不可读:$html = <<<EOD&nbsp; &nbsp; <!--{hello}-->&nbsp; &nbsp; <div class="novalue">&nbsp; &nbsp; &nbsp; &nbsp; <a>URL</a>&nbsp; &nbsp; </div>&nbsp; &nbsp; <!--{/hello}-->EOD;echo preg_replace('#\h*<!--({.+?})-->#', '$1', $html);输出:{hello}&nbsp; &nbsp; <div class="novalue">&nbsp; &nbsp; &nbsp; &nbsp; <a>URL</a>&nbsp; &nbsp; </div>{/hello}解释:#&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# regex delimiter&nbsp; \h*&nbsp; &nbsp; &nbsp; &nbsp;# 0 or more horizontal spaces&nbsp; <!--&nbsp; &nbsp; &nbsp; # literally, begin comment&nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# start group 1&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp;# opening curly brace&nbsp; &nbsp; .+?&nbsp; &nbsp; &nbsp;# 1 or more any character, not greedy&nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp;# closing curly brace&nbsp; )&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# end group 1&nbsp; -->&nbsp; &nbsp; &nbsp; &nbsp;# literally, end comment#&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# regex delimiter

子衿沉夜

\s*从正则表达式的开头删除。/\<\!\-\-\{(.+?)\}\-\-\>/s然后替换为{$1}
打开App,查看更多内容
随时随地看视频慕课网APP