我有这个函数来限制文本,比如说 50 个字符,就像上面一样:
$bio = limit_text($bio, 50);
function limit_text($text, $length){ // Limit Text
if(strlen($text) > $length) {
$text = substr($text, 0, strpos($text, ' ', $length));
}
return $text;
}
这应该回显如下内容:
您好,这是一个限制为 50 个字符的文本,这很棒......
问题是该函数显示最后一个标点符号,看起来不专业。就像这个例子一样:
您好,这是一个限制为 50 个字符的文本,末尾有一个逗号,...
有没有办法使函数不显示最后一个标点符号?
谢谢!
<?php
$text="Hello, this is a text limited to 50 chars and it has a comma at the end.";
//$text = preg_replace("/[^a-zA-Z 0-9]+/", " ", $text); //bad
$text=rtrim($text,",.;:- _!$&#"); // good select what you want to remove
echo $text;
这应该可以完成工作,ctype_punct
检查给定字符串中的所有非字母数字字符。
function limit_text($text, $length){ // Limit Text
if(strlen($text) > $length) {
$text = substr($text, 0, strpos($text, ' ', $length));
if(ctype_punct(substr($text,-1))
$text=substr($text,0,-1);
}
return $text;
}
return rtrim($text, ',') . '...'; // That is if you only care about the ',' character
你可以
像这样的函数来首先解析$text
:
$text = preg_replace("/[^a-zA-Z 0-9]+/", " ", $text);