php - 自动 <p> 正则表达式 - 需要修复

标签 php html regex

我有这个功能(我在 Stackoverflow 的某处找到的)自动添加 <p>输出字符串中的标签。

function autop ($string) {

    // Define block tags
    $block_tag_list = array ('address', 'applet', 'article', 'aside', 'audio', 'blockquote', 'button', 'canvas', 'center', 'command', 'data', 'datalist', 'dd', 'del', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'iframe', 'ins', 'isindex', 'li', 'map', 'menu', 'nav', 'noframes', 'noscript', 'object', 'ol', 'output', 'p', 'pre', 'progress', 'section', 'script', 'summary', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'ul', 'video');

    $tags = '<' . implode ('[^>]*>|<', $block_tag_list) . '[^>]*>';

$pattern = <<<PATTERN
/
(\A|\\n\\n)(?!$tags) # Start of string or two linebreaks or anything but a block tag
(.+?) # Just about anything
(\Z|\\n\\n) # End of string or two line breaks
/isex
PATTERN;

    $string = str_replace ("\r\n", "\n", $string);
    $string = str_replace ("\r\t", "", $string);
    $string = str_replace ("\n\t", "", $string);
    $string = str_replace ("\t", "", $string);
    $string = preg_replace ($pattern, "'\\1<p>' . nl2br ('\\2') . '</p>\\3'", $string);
    $string = preg_replace ($pattern, "'\\1<p>' . nl2br ('\\2') . '</p>\\3'", $string);
    $string = str_replace ('\"', "&quot;", $string);

    return $string;
}

具有这种类型的字符串:

<h1>Title</h1>

This will be wrapped in a p tag

This should be wrapped in a p tag too

输出

<h1>Title</h1>

<p>This will be wrapped in a p tag</p>

<p>This should be wrapped in a p tag too</p>

它工作正常,但有一个问题:它包装了紧跟在 <p> 之后的 HTML 标签。其他标签<p>标签,搞砸代码。如果 HTML 标记位于 <h1> 之后,则不会发生这种情况。或任何其他 block 标记。

制作双 preg_replace一个就解决了问题,但是如果像前面的例子一样有两个段落,它只包含第一个而不是第二个。

我觉得这只是一个小的变化,可以让它“滴答作响”,但我想不通。

也许如果有人有天才罢工...:)

最佳答案

我不确定您是否会一直对您的解决方案感到满意,但您应该得到您想要用它做的事情(观看第 5 行添加的 ?=):

$pattern = <<<PATTERN
/
(\A|\\n\\n)(?!$tags) # Start of string or two linebreaks or anything but a block tag
(.+?) # Just about anything
(?=\Z|\\n\\n) # End of string or two line breaks
/isex
PATTERN;

如果没有这个,之前的边界 \Z 将消耗下一个 \A,因此这将不再匹配。当然,删除双 preg_replace

希望这对您有所帮助。

关于php - 自动 <p> 正则表达式 - 需要修复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11525328/

相关文章:

ruby - 正则表达式用逗号和空格分割字符串,但忽略带连字符的单词?

php - 设置 session 变量以在 Symfony Controller 中使用重定向 PHPUnit 测试

php - mail() php 不以 html 格式发送

php - TCPDF 对齐标题

php - 在 Lumen 5.2 中配置日志轮换

javascript - 在保持文本插入光标的同时防止移动默认键盘

html - 导航悬停时背景图像发生变化

Python 简单的正则表达式

html - 无法在 CSS 中使用逗号组合选择器

regex - 当第二个模式不匹配时,以逗号分隔的模式地址执行 sed 命令