0

我在 Wordpress 中开发,但我的 PHP 知识很少,标题只显示第一个单词,我该如何更改?这就是我认为它仅限于第一个单词的地方。

function ShortenTitle($title){
// Change to the number of characters you want to display
$chars_max = 100;
$chars_text = strlen($title);
$title = $title."";
$title = substr($title,0,$chars_max);
$title = substr($title,0,strrpos($title,' '));
if ($chars_title > $chars_max)
{
$title = $title."...";
}
return $title;
}
function limit_content($str, $length) {
  $str = strip_tags($str);
  $str = explode(" ", $str);
  return implode(" " , array_slice($str, 0, $length));
}
4

2 回答 2

1

if ($chars_title > $chars_max)应该if ($chars_text > $chars_max)

试试这个:

function ShortenTitle($title) {
    $title = trim($title);
    $chars_max = 100;
    if (strlen($title) > $chars_max) {
        $title = substr($title, 0, $chars_max) . "...";
    }
    return $title;
}

稍微清理了一下。

于 2013-01-11T16:13:56.470 回答
1

trim函数从字符串的末尾删除空格,我假设这是你试图用这个做的

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

此外,为了安全/准确,您可能应该在计算长度之前进行修剪。试试这个:

function ShortenTitle($title){
    // Change to the number of characters you want to display
    $chars_max = 100;
    $new_title = substr(trim($title),0,$chars_max);
    if (strlen($title) > strlen($new_title)) {
        $new_title .= "...";
    }
    return $new_title;
}
于 2013-01-11T16:16:23.373 回答