我的函数中有此代码。php文件:
function user_content_replace($content) {
// it\'s not a URL, let\'s apply the replacement
if (!filter_var($string, FILTER_VALIDATE_URL)) {
$replacement = \'$1.</p><p>$2\';
return preg_replace("/([^\\\\.]*\\\\.[^\\\\.]*\\\\.[^\\\\.]*){1}\\\\.([^\\\\.]*)/s", $replacement, $content);
} else { // it\'s a URL, just return the string
return $content;
}
}
add_filter(\'the_content\',\'user_content_replace\', 99);
此代码将内容中的每三个点替换为点+封闭+开放段落。这是因为这是目前格式化大量非格式化文本和帖子的最佳方式。
但是:此代码也会更改Images URLs 因此,我所有的图像在扩展之前不包含点,但**imagename.</p><p>jpg**
而不是imagename.jpg
即使我把URL验证-同样的问题。有什么建议吗?
最合适的回答,由SO网友:Max Yudin 整理而成
<?php
$string = \'Sentence 1. Sentence 2? Sentence 3! Sentence 4... Sentence 5… Sentence 6! Sentence 7. Sentence 8. Sentence 9… Sentence 10... Sentence 11. \';
$sentences_per_paragraph = 3; // settings
$pattern = \'~(?<=[.?!…])\\s+~\'; // some punctuation and trailing space(s)
$sentences_array = preg_split($pattern, $string, -1, PREG_SPLIT_NO_EMPTY); // get sentences into array
$sentences_count = count($sentences_array); // count sentences
$output = \'\'; // new content init
// see PHP modulus
for($i = 0; $i < $sentences_count; $i++) {
if($i%$sentences_per_paragraph == 0 && $i == 0) { //divisible by settings and is first
$output .= "<p>" . $sentences_array[$i] . \' \'; // add paragraph and the first sentence
} elseif($i%$sentences_per_paragraph == 0 && $i > 0) { //divisible by settings and not first
$output .= "</p><p>" . $sentences_array[$i] . \' \'; // close and open paragraph, add the first sentence
} else {
$output .= $sentences_array[$i] . \' \'; // concatenate other sentences
}
}
$output .= "</p>"; // close the last paragraph
echo $output;
Note: 这是一个非常粗糙的代码,无法检查更深层次的问题。
有关详细信息:
SO网友:Eager2Learn
感谢@Max Yudin,这是我问题的答案:
function user_content_replace($content) {
$sentences_per_paragraph = 3; // settings
$pattern = \'~(?<=[.?!…])\\s+~\'; // some punctuation and trailing space(s)
$sentences_array = preg_split($pattern, $content, -1, PREG_SPLIT_NO_EMPTY); // get sentences into array
$sentences_count = count($sentences_array); // count sentences
$output = \'\'; // new content init
// see PHP modulus
for($i = 0; $i < $sentences_count; $i++) {
if($i%$sentences_per_paragraph == 0 && $i == 0) { //divisible by settings and is first
$output .= "<p>" . $sentences_array[$i] . \' \'; // add paragraph and the first sentence
} elseif($i%$sentences_per_paragraph == 0 && $i > 0) { //divisible by settings and not first
$output .= "</p><p>" . $sentences_array[$i] . \' \'; // close and open paragraph, add the first sentence
} else {
$output .= $sentences_array[$i] . \' \'; // concatenate other sentences
}
}
$output .= "</p>"; // close the last paragraph
echo $output;
}
add_filter(\'the_content\',\'user_content_replace\', 99);