2013-04-26 142 views
0

我現在正在爲這一天掙扎半天,我似乎無法做到。我在我的wordpress網站有一個自定義功能,它會自動創建一個摘錄。這一切都很順利,但對於一些(我想邏輯)的原因,它也切斷了<br />標籤,因爲它有一個空間。Preg_split擰緊BR標籤?

如何解決這個問題?這與preg_split函數有關嗎?

下面是我的代碼:

function custom_wp_trim_excerpt($text) { 
$raw_excerpt = $text; 
if ('' == $text) { 
    //Retrieve the post content. 
    $text = get_the_content(''); 

    //Delete all shortcode tags from the content. 
    $text = strip_shortcodes($text); 

    $text = apply_filters('the_content', $text); 
    $text = str_replace(']]>', ']]&gt;', $text); 

    $allowed_tags = '<p>,<br>,<br/>,<br />,<a>,<em>,<strong>,<img>'; /*** MODIFY THIS. Add the allowed HTML tags separated by a comma.***/ 
    $text = strip_tags($text, $allowed_tags); 

    $excerpt_word_count = 40; /*** MODIFY THIS. change the excerpt word count to any integer you like.***/ 
    $excerpt_length = apply_filters('excerpt_length', $excerpt_word_count); 

    $excerpt_end = ' <a href="'. get_permalink($post->ID) . '">' . '...' . '</a>'; 
    $excerpt_more = apply_filters('excerpt_more', ' ' . $excerpt_end); 

    $words = preg_split("/[\n\r\t ]+/", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY); 
    if (count($words) > $excerpt_length && $words) { 
     array_pop($words); 
     $text = implode(' ', $words); 
     $text = $text . $excerpt_more; 
    } else { 
     $text = implode(' ', $words); 
    } 
} 
return apply_filters('wp_trim_excerpt', $text, $raw_excerpt); 
} 
remove_filter('get_the_excerpt', 'wp_trim_excerpt'); 
add_filter('get_the_excerpt', 'custom_wp_trim_excerpt'); 

謝謝!

回答

0

您可以添加這讓所有的HTML中斷字符相同的:

$text = preg_replace('!<br ?/>!i','<br>',$text); 

這些行之前:

$allowed_tags = '<p>,<br>,<a>,<em>,<strong>,<img>'; /*** MODIFY THIS. Add the allowed HTML tags separated by a comma.***/ 
$text = strip_tags($text, $allowed_tags); 

當你在做preg_split("/[\n\r\t ]+/",$text)你在分裂的空間打破<br />字符。

您還可以簡化正則表達式中preg_split()聲明:

$words = preg_split("!\s+!", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY); 

由於你允許他們可能包含空格太雖然其他標籤。

+0

謝謝,這幫了我! – RobbertT 2013-04-26 09:19:57