Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/247.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
限制文本的正确方法?PHP_Php - Fatal编程技术网

限制文本的正确方法?PHP

限制文本的正确方法?PHP,php,Php,有一种方法可以使用substr $testo = $news['testo']; $testo = strip_tags($testo); echo "<p>".substr($testo,0,200)."</p>"; $testo=$news['testo']; $testo=带标签($testo); echo“”.substr($testo,0200)。“”; 我做了几个测试,发现substr不计算空白。我怎么能让他数一数呢 这是一个问题,因为这篇文章每次给我

有一种方法可以使用
substr

$testo = $news['testo'];

$testo = strip_tags($testo);

echo "<p>".substr($testo,0,200)."</p>";
$testo=$news['testo'];
$testo=带标签($testo);
echo“”.substr($testo,0200)。“”;
我做了几个测试,发现
substr
不计算空白。我怎么能让他数一数呢

这是一个问题,因为这篇文章每次给我的字符数不同。

请尝试下面的代码

$testo = $news['testo'];
$testo = strip_tags($testo);
$count_var = preg_replace('[^\s]', '', $testo);
$count = strlen($count_var);

这样做不需要任何正则表达式(如Ruchish的回答所示)
只用

编辑 当然,如果您希望将空格计算到子字符串中,您可以执行以下操作

substr_count(substr($fooString,$start,$length), " ");
在哪里

$start
是子集的起始位置

$length
是substr的长度

substr将返回字符串的一部分,不计算……您的问题不够清楚。您想使用<代码>子字符串< /> >限制文本,但您没有得到预期的结果,认为问题是在空白空间中进行的吗?请编辑您的问题。
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;
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;