2011-01-20 76 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

相关问题