2011-01-20 65 views
1

我做了這個功能,以限制輸出字符串的長度,用正則表達式去除標點符號嗎?

/* limit the lenght of the string */ 
function limit_length($content, $limit) 
{ 
    # strip all the html tags in the content 
    $output = strip_tags($content); 

    # count the length of the content 
    $length = strlen($output); 

    # check if the length of the content is more than the limit 
    if ($length > $limit) 
    { 
     # limit the length of the content in the output 
     $output = substr($output,0,$limit); 

     $last_space = strrpos($output, ' '); 

     # add dots at the end of the output 
     $output = substr($output, 0, $last_space).'...'; 
    } 

    # return the result 
    return $output; 
} 

它工作正常,但我認爲這是不完美的......比如,我有串在本文中,

Gender Equality; Radicalisation; Good Governance, Democracy and Human Rights; 

,這是我如何使用功能,

echo limit_length($item['pg_description'], 20); 

然後返回,

Gender Equality;... 

當你想告訴人們內容/行中有更多文本時,你可以用它看起來不太好用;...

我在想如果有可能使用正則表達式來檢查在...之前是否存在任何標點符號,然後將其刪除。

可能嗎?我如何編寫表達式來改進我的功能,以便可以做到「防彈」?

謝謝。

回答

2
$str = preg_replace("/\W+$/", "", $str); 
+0

的感謝! – laukok 2011-01-20 19:26:17

1

要刪除除信件直接前面的三個階段(根據需要調整)以外的任何其他:爲幫助

$foo = preg_replace("[a-zA-Z0-9]+\.{3}", "...", $foo);

+0

據推測,他將在添加句號之前刪除標點符號:) – 2011-01-20 19:07:06

相關問題