php - 如何在空格后分割内容

标签 php

我只是 PHP 新手,

现在我在分割内容功能方面遇到了麻烦, 我有一个如下所示的字符串:

$tring = 'World Cup 2014 draw: England's chances of landing tough group rise';

我的分割内容代码:

 if(strlen($string)<$width){
        return $string;
    }
    $string = substr($string,0,$width);
    $string = $string.'...';
    return $string;

结果是:

2014 年世界杯抽签:英格兰队的机会......,

当我插入时

$string = substr($string,0,strrpos($string,' '));

它看起来像这样:

2014 年世界杯抽签:英格兰队的机会...,

现在我希望我的字符串看起来像这样:

2014 年世界杯抽签:英格兰队登陆的机会...
我该怎么办 ?感谢您的帮助

最佳答案

这将在 $width 字符处分割内容,但如果它落在一个单词上,它将匹配单词的末尾(所以它实际上是 $width+[num chars 直到结尾)如果在单词中间,则为单词]。“单词”被定义为字母、数字、下划线、连字符或单引号。这将把“England”或“England's”或“pre-text”等内容解释为整个单词。

$width = 20;
$text = "World Cup 2014 draw: England's chances of landi-ng tough group rise";
preg_match("~^.{".($width-1)."}([\w'-]+)?~i",$text,$m);
$newtext = $m[0].'...';
echo $newtext.'<br/>';

关于php - 如何在空格后分割内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20366210/

相关文章:

php - symfony2 Doctrine onetoone 完整示例

javascript - 可以将 Wordpress 插件转换为在非 WP 网站上使用吗?

php - 使用 array_count_values 并得到 "Can only count STRING and INTEGER values!"错误

php - Laravel mssql 驱动支持

php - Imagick:queryFontMetrics() 函数在 Windows 和 Linux 上给出不同的结果

php - 将 OAuth1 附加到 GuzzleHttp\Client

php - 使用 echo $variablename 时无法打印表单变量

PHP $_GET 从表单提交到同一页面

php - JavaScript/jQuery 和 PHP Ajax 强制报错

php - 无法编辑 overflow-x :hidden