Formatter скрипт из WordPress class Formatter function format text br

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
* Formatter — скрипт из WordPress
*/
class Formatter {
function format($text, $br = 1) {
$text = $text . "\n"; // just to make things a little easier, pad the end
// <br> --> <br />
$text = str_replace('<br>', '<br />', $text);
$text = str_replace('<br/>', '<br />', $text);
$text = preg_replace('|<br />\s*<br />|', "\n\n", $text);
// Space things out a little
$allblocks = '(?:table|thead|tfoot|caption|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|form|map|area|blockquote|address|math|style|input|p|h[1-6]|hr)';
$text = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $text);
$text = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $text);
// cross-platform newlines
$text = str_replace(array("\r\n", "\r"), "\n", $text);
if ( strpos($text, '<object') !== false ) {
// no pee inside object/embed
$text = preg_replace('|\s*<param([^>]*)>\s*|', "<param$1>", $text);
$text = preg_replace('|\s*<embed([^>]*)>\s*|', "<embed$1>", $text);
$text = preg_replace('|\s*</param>\s*|', '</param>', $text);
$text = preg_replace('|\s*</embed>\s*|', '</embed>', $text);
}
$text = preg_replace("/\n\n+/", "\n\n", $text); // take care of duplicates
$text = preg_replace('/\n?(.+?)(?:\n\s*\n|\z)/s', "<p>$1</p>\n", $text); // make paragraphs, including one at the end
$text = preg_replace('|<p>\s*?</p>|', '', $text); // under certain strange conditions it could create a P of entirely whitespace
$text = preg_replace('!<p>([^<]+)\s*?(</(?:div|address|form)[^>]*>)!', "<p>$1</p>$2", $text);
$text = preg_replace('|<p>|', "$1<p>", $text );
$text = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $text); // don't pee all over a tag
$text = preg_replace("|<p>(<li.+?)</p>|", "$1", $text); // problem with nested lists
$text = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $text);
$text = str_replace('</blockquote></p>', '</p></blockquote>', $text);
$text = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', "$1", $text);
$text = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $text);
if ($br) {
$text = preg_replace_callback('/<(script|style).*?<\/\\1>/s', create_function('$matches', 'return str_replace("\n", "<NL />", $matches[0]);'), $text);
$text = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $text); // optionally make line breaks
$text = str_replace('<NL />', "\n", $text);
}
$text = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $text);
$text = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $text);
if (strpos($text, '<pre') !== false)
$text = preg_replace_callback('!(<pre.*?>)(.*?)</pre>!is', 'clean_pre', $text );
$text = preg_replace( "|\n</p>$|", '</p>', $text );
return $text;
}
}