Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/280.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.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
如何仅显示文章的前x个字符作为预览(PHP)?_Php_Function - Fatal编程技术网

如何仅显示文章的前x个字符作为预览(PHP)?

如何仅显示文章的前x个字符作为预览(PHP)?,php,function,Php,Function,我想知道,作为预览,您如何只显示帖子的第一个“x”字符。有点像StackOverflow在显示问题列表时所做的 The quick brown fox jumps over the lazy dog 去 The quick brown fox jumps... 我不想在中间讲一个字。我在想explode函数在每个空间分解,explode(“,$post),但我不太确定是否有其他方法。谢谢使用带有偏移量的strpos()找到一个方便放置的空间,并使用substr()在那里切片字符串。尝试: p

我想知道,作为预览,您如何只显示帖子的第一个“x”字符。有点像StackOverflow在显示问题列表时所做的

The quick brown fox jumps over the lazy dog

The quick brown fox jumps...
我不想在中间讲一个字。我在想explode函数在每个空间分解,explode(“,$post),但我不太确定是否有其他方法。谢谢

使用带有偏移量的
strpos()
找到一个方便放置的空间,并使用
substr()
在那里切片字符串。

尝试:

preg_match('/^.{0,30}(?:.*?)\b/iu', $text, $matches);
最多匹配30个字符,然后在下一个最近的分词处分词

注:如果x美元是8美元,那么输出将是“the”,而不是“the quick”

也可以使用explode

$str = "The quick brown fox jumps over the lazy dog";
$s = explode(" ",$str);
$x=14;
$final="";
foreach ($s as $k){
    if ( strlen($final) <= $x ){
        $final.="$k ";
    }else{ break; }
}
print "-> $final\n";
敏捷的棕色狐狸跳过了懒惰的狗; $s=爆炸(“,$str”); $x=14; $final=“”; foreach($s作为$k){ if(strlen($final)strpos()将提供您所需的。此函数将提供您所需的

function getPreview($text, $minimumLength=60){
     return substr($text,0,strpos($text,' ',$minimumLength)) . '...';
}

注意:我还没有测试该函数

@Alix-实际上,经过仔细考虑,您根本不需要分组-
$matches[0]
正确吗?
function getPreview($text, $minimumLength=60){
     return substr($text,0,strpos($text,' ',$minimumLength)) . '...';
}