为什么一种类型的解析字符串在错误的地方回显?

时间:2018-07-19 00:46:12

标签: php html regex

我正在使用BBCode的网站上使用格式工具栏,并在回显我的内容之前使用以下代码解析某些格式标记:

$content = htmlspecialchars($row['postContent'], ENT_QUOTES);

//Parse BB Code
$patterns = array
(
    "#\[b\](.*?)\[\/b\]#",
    "#\[i\](.*?)\[\/i\]#",
    "#\[u\](.*?)\[\/u\]#",    
    "#\[quote\](.*?)\[\/quote\]#"                                       
);

$replacements = array
(
    "<b>$1</b>",
    "<i>$1</i>",
    "<u>$1</u>",
    "<blockquote class=\"user-quote\"><p class=\"quote-text\">$1</p></blockquote>"                          
);

$content = preg_replace($patterns, $replacements, $content);

我遇到的问题是最终标签没有在适当的位置回显。我目前在以下HTML内回显了所有$row['postContent']

<div class="text">                                           
    <p id="'.$row['postID'].'">
        '.$content.'
    </p>
</div>

所有格式标签(包括我在本文中未显示的其他格式标签)都放在<p id="blah"></p>元素中,因此根据我对段落元素的CSS样式进行格式化。由于某些原因,<blockquote class=\"user-quote\"><p class=\"quote-text\">$1</p></blockquote>在这些标签之后被回显,当我在检查器中查看代码时,它看起来像:

<div class="text">                                           
    <p id="blah">

    </p>
    <div class="user-quote">
      ::before
        <p class="quote-text">foo bar</p>
      ::after
    </div>        
</div>

足够奇怪的是,如果我查看页面的源代码,它似乎可以正确地回显,但是在检查器中却不是这种情况,并且在我的页面上看起来确实是不正确的,特别是如果我包含的常规文本不在BBCode标签内。如果这样做,div末尾会出现一个奇怪的“幻影” <p></p>

<div class="text">                                           
    <p id="blah">

    </p>
    <div class="user-quote">
      ::before
        <p class="quote-text">foo bar</p>
      ::after
    </div>  
    "
    here is some non-formatted text

    "
    <p></p>      
</div>

我尝试了很多事情,例如删除某些CSS样式(我以为::before::after是罪魁祸首),然后将标签从<blockquote>更改为{{1 }},但没有任何效果。为什么会发生这种情况?也许我的疲劳使我错过了一些显而易见的事情。

如果有帮助,这就是我要从数据库中回显的确切内容:

<div>

[EDIT]如果我切换内容的格式...

[quote]some text[/quote]

here is some non-formatted text

...然后产生正确的结果。我仍然不确定为什么这样,或者为什么其他格式会产生错误的结果。我当然希望用户能够在quote标记后发布常规文本。

1 个答案:

答案 0 :(得分:1)

您已经通过说出if I view the source code for the page it appears to be echoed correctly, but this isn't the case in the inspector,

正确地调试了问题

HTML检查器不是用于生成页面的HTML,而是浏览器如何设法确定需要显示的内容。

如果您查看“ P”元素的规范-https://developer.mozilla.org/en-US/docs/Web/HTML/Element/p-您会发现,如果在<p>后面加上<blockquote>,则假定<p>为关闭,因此您会在检查器<p></p><blockquote>blah</blockquote>中看到(紧跟着</p>,它不知道要做什么,可能会使用或已丢弃,并且可能不会在检查器中显示-不太确定)。

相关问题