限制文本的正确方法?.PHP


the right way to limit text? PHP

有一种方法可以用substr来计算空格?

$testo = $news['testo'];
$testo = strip_tags($testo);
echo "<p>".substr($testo,0,200)."</p>";

做了几次测试,我发现substr不计算空格。我怎么能告诉他数数呢?

这是一个问题,因为它每次为文章提供了不同数量的字符。

你不需要任何正则表达式来做到这一点(如Ruchish的答案所示)
只需使用substr_count

$fooString = "Hello world string!";
$count = substr_count($fooString, " ");
echo $count; // --> 2

编辑

当然,如果您希望将空格计数到子字符串中,您可以随时执行以下操作:

substr_count(substr($fooString,$start,$length), " ");

哪里

  $start是子集
的起始位置 $length是子串的长度

尝试下面的代码。

$testo = $news['testo'];
$testo = strip_tags($testo);
$count_var = preg_replace('[^'s]', '', $testo);
$count = strlen($count_var);
if(strlen($testo)>=200)
{
//limit text
    $testo =substr($testo,0,200);
//get last space character
    $space=strrpos($testo, ' ');
// finished
    $testo =substr($testo ,0,$space)." ...";
}
echo $testo;