【问题标题】:Remove the punctuation mark with regular expression?用正则表达式去掉标点符号?
【发布时间】:2011-01-20 19:01:01
【问题描述】:

我做了这个函数来限制输出中字符串的长度,

/* 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;...

当你想告诉人们内容/行中有更多文本时,;... 看起来不太好。

我在想是否可以使用正则表达式来检查... 之前是否存在任何标点符号,然后将其删除。

有可能吗?我如何编写表达式来改进我的功能,以便有点“防弹”?

谢谢。

【问题讨论】:

    标签: php regex preg-match substr punctuation


    【解决方案1】:
    $str = preg_replace( "/\W+$/", "", $str );
    

    【讨论】:

      【解决方案2】:

      要删除三个句点前面的字母以外的任何内容(根据需要进行调整):

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

      【讨论】:

      • 想必他会在添加句点之前删除标点符号:)
      • 我会倾向于 after 添加句点,因为标点符号看起来不错或放错了位置,如果不是因为它位于 sn 的末尾-p.
      猜你喜欢
      • 1970-01-01
      • 2012-07-27
      • 1970-01-01
      • 2013-11-22
      • 2013-05-12
      • 2014-06-12
      • 1970-01-01
      相关资源
      最近更新 更多