您可以将其与regEx匹配,并轻松选择要返回的段落数量。
// in context
function triangle_x_excerpt( $text, $raw_excerpt ) {
$content = apply_filters( \'the_content\', get_the_content() );
$text = ( preg_match( sprintf( \'~(<p>.+?</p>){%d}~i\', 1 ), $content, $matches ) ) ? $matches[ 0 ] : $content;
return preg_replace( "/<img[^>]+\\>/i", "", $text );
}
<小时>
$text = prefix_get_p( $content, 1);
<小时>
function prefix_get_p($content, $max = 1)
{
$max = is_numeric($max) ? absint($max) : 1;
return (preg_match(sprintf(\'~(<p>.+?</p>){%d}~i\', $max), $content, $matches)) ? $matches[0] : $content;
}
echo "Limit 1" . PHP_EOL;
echo prefix_get_p(\'<p>aaaaa</p><p>bbbbb</p><p>ccccc</p><p>dddddd</p><p>eeeeeee</p><p>ffffff</p>\', 1); // <p>aaaaa</p>
echo "Limit 3" . PHP_EOL;
echo prefix_get_p(\'<p>aaaaa</p><p>bbbbb</p><p>ccccc</p><p>dddddd</p><p>eeeeeee</p><p>ffffff</p>\', 3); // <p>aaaaa</p><p>bbbbb</p><p>ccccc</p>
echo "Limit 2" . PHP_EOL;
echo prefix_get_p(\'<p>aaaaa</p><p>bbbbb</p><p>ccccc</p><p>dddddd</p><p>eeeeeee</p><p>ffffff</p>\', 2); // <p>aaaaa</p><p>bbbbb</p>