我在网站上列出了1500种产品。默认代码
下面的页面标题都是相同的$title="Detail Turkish Property For Sale in Turkey";
为了使页面标题更能描述产品,我想从页面产品描述中获得前10个单词,以显示在页面标题中。
我已经试过这个例子没有改变,
$title = stripslashes(substr($emlaklist->aciklama,0,80));
请您提出解决这个问题的建议。
下面是一个函数复制从我如何截断字符串到前20个字在PHP?,所以我不认为这是功劳,但它似乎确实做了你正在寻找的。
function limit_text($text, $limit) {
if (str_word_count($text, 0) > $limit) {
$words = str_word_count($text, 2);
$pos = array_keys($words);
$text = substr($text, 0, $pos[$limit]) . '...';
}
return $text;
}
从我在评论中看到的,你首先要确保你的变量 ($emlaklist
) 已经设置,当你想把它的值附加到$title
变量。
一般情况下,您可能会尝试将以$emlaklist = ..
开头的代码部分复制到$title =
之前的位置,但最有可能的是这将是一个数据库请求,因此您可能需要考虑其他代码,这有助于获得该值…
除此之外,这里的其他答案将能够很好地处理缩短描述等。
这应该可以正常工作。比如:
$title="Detail Turkish Property For Sale in Turkey";
$description = implode(' ',array_slice(explode(' ', $title), 0, 10));
这里是php手册的链接,用于解释使用的函数:
爆炸函数- http://php.net/manual/en/function.explode.php
Array_slice函数- http://au2.php.net/manual/en/function.array-slice.php
内爆函数- http://au2.php.net/manual/en/function.implode.php
古德勒克。
您需要某种处理字符串的方法,因为检查单词比检查字符稍微复杂一些。这个例子实际上取自Laravel框架,并做了一些小的调整,使其能够独立工作。
/**
* @param {String} the value to shorten
* @param {Integer} number of words allowed
* @param {String} what to put on the end of the string
* @return {String}
*/
function words($value, $words = 100, $end = '...')
{
preg_match('/^'s*+(?:'S++'s*+){1,'.$words.'}/u', $value, $matches);
if ( ! isset($matches[0])) return $value;
if (strlen($value) == strlen($matches[0])) return $value;
return rtrim($matches[0]).$end;
}
那么你可以这样写:
$title = words($title, 10, '<a href="#">Read more</a>');
在你的代码中使用:
$title = words($emlaklist->aciklama, 10, '');
确保函数被声明了,如果你想的话,可以从这里复制粘贴。还要确保$emlaklist->aciklama
包含您需要的内容。