<p>
出力用の文字列にタグを自動的に追加するこの関数(Stackoverflowのどこかにあります)があります。
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 ('\"', """, $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>
正常に動作しますが、1つの問題があります。それは、タグの直後にあるHTMLタグを<p>
他の<p>
タグにラップし、コードをねじ込むことです。<h1>
HTMLタグがまたは他のブロックタグの後にある場合は発生しません。
ダブルpreg_replace
をシングルにすることで問題は解決しますが、前の例のように2つの段落がある場合は、最初の段落のみをラップし、2番目の段落はラップしません。
それはほんの小さな変化であり、それを「カチカチ」させることができると私は感じますが、私はそれを理解することができません。
多分誰かが天才のストライキをした場合...:)