php 文本取前10条,关于substring:PHP-获取文本的前两个句子?

我的变量$content包含我的文本。 我想从$content创建一个摘录并显示第一个句子,如果该句子少于15个字符,我想显示第二个句子。

我已经尝试从文件中剥离前50个字符,并且它的工作原理是:

但是我对结果不满意(我不想删节)。

是否有一个PHP函数可以获取整个单词/句子,而不仅仅是substr?

非常感谢!

什么是唱歌?

(相关)将多字节字符串截断为n个字符。 那里的解决方案削减了字边界。 如果您不关心句子,而仅关心单词,则为重复项。

可能重复:stackoverflow.com/questions/79960/

我想通了,虽然很简单:

$content ="My name is Luka. I live on the second floor. I live upstairs from you. Yes I think you've seen me before.";

$dot =".";

$position = stripos ($content, $dot); //find first dot position

if($position) { //if there's a dot in our soruce text do

$offset = $position + 1; //prepare offset

$position2 = stripos ($content, $dot, $offset); //find second dot using offset

$first_two = substr($content, 0, $position2); //put two first sentences under $first_two

echo $first_two . '.'; //add a dot

}

else {  //if there are no dots

//do nothing

}

?>

在"我的名字叫卢卡(Luka。我在纽约1.1.1953出生)"处休息。 =>"我叫Luka。我1岁。"

@Tom?Fejfar在这种情况下,将$dot ="."更改为$dot ="."(在句点后添加一个空格)

附带说明一下,如果您有引起感叹号的地方,则可以执行str_replace将其替换为句点。 $content = str_replace(! , . , $content);

这是我编写的一种快速帮助方法,用于获取给定文本主体的前N个句子。它考虑了句点,问号和感叹号,默认为2个句子。

function tease($body, $sentencesToDisplay = 2) {

$nakedBody = preg_replace('/\s+/',' ',strip_tags($body));

$sentences = preg_split('/(\.|\?|\!)(\s)/',$nakedBody);

if (count($sentences) <= $sentencesToDisplay)

return $nakedBody;

$stopAt = 0;

foreach ($sentences as $i => $sentence) {

$stopAt += strlen($sentence);

if ($i >= $sentencesToDisplay - 1)

break;

}

$stopAt += ($sentencesToDisplay * 2);

return trim(substr($nakedBody, 0, $stopAt));

}

单词有一个-自动换行

示例代码:

for ($i = 10; $i < 26; $i++) {

$wrappedtext = wordwrap("Lorem ipsum dolor sit amet", $i,"

");

echo substr($wrappedtext, 0, strpos($wrappedtext,"

")) ."

";

}

输出:

Lorem

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum

Lorem ipsum dolor

Lorem ipsum dolor

Lorem ipsum dolor

Lorem ipsum dolor

Lorem ipsum dolor sit

Lorem ipsum dolor sit

Lorem ipsum dolor sit

Lorem ipsum dolor sit

Lorem ipsum dolor sit

Ctrl + L添加链接。

wordwrap不会截断字符串,而只是在特定位置插入换行符。 mb_strimwidth将截断,但不遵守单词边界。

是的,您是对的...对不起,那个...但是您可以做类似substr($ wrappedtext,0,strpos($ wrappedtext,$ delimiter))的事情:)

@Paul仍然不遵守单词边界

刚刚尝试过...它确实确实照顾了单词边界!您不能将true作为第四个参数传递...

@Paul请使用示例代码(无论如何都是这样的习惯)更新您的答案,以证明您的观点。如果有的话,我会删除掉downvote,但那时我真的很惊讶。

我将示例代码+输出添加到我的"答案"中

@Paul如果源字符串中较早的位置已经有换行符,则会失败。尝试" Lorem n ipsum dolor sit amet"。 wordwrap确实遵守单词边界,但strpos则没有。

我知道这是一篇旧文章,但我一直在寻找相同的东西。

preg_match('/^([^.!?]*[\.!?]+){0,2}/', strip_tags($text), $abstract);

echo $abstract[0];

我在一个网站上编写了一个函数来执行类似操作。我相信可以对其进行调整以从中获得确切的结果。

基本上,您给它一个文本字符串和想要修剪的单词数量。然后它将修剪到该单词数量。如果找到的最后一个单词没有结束句子,它将持续超过您指定的单词数,直到到达句子结尾。希望能帮助到你!

//This function intelligently trims a body of text to a certain

//number of words, but will not break a sentence.

function smart_trim($string, $truncation) {

$matches = preg_split("/\s+/", $string);

$count = count($matches);

if($count > $truncation) {

//Grab the last word; we need to determine if

//it is the end of the sentence or not

$last_word = strip_tags($matches[$truncation-1]);

$lw_count = strlen($last_word);

//The last word in our truncation has a sentence ender

if($last_word[$lw_count-1] =="." || $last_word[$lw_count-1] =="?" || $last_word[$lw_count-1] =="!") {

for($i=$truncation;$i

unset($matches[$i]);

}

//The last word in our truncation doesn't have a sentence ender, find the next one

} else {

//Check each word following the last word until

//we determine a sentence's ending

for($i=($truncation);$i

if($ending_found != TRUE) {

$len = strlen(strip_tags($matches[$i]));

if($matches[$i][$len-1] =="." || $matches[$i][$len-1] =="?" || $matches[$i][$len-1] =="!") {

//Test to see if the next word starts with a capital

if($matches[$i+1][0] == strtoupper($matches[$i+1][0])) {

$ending_found = TRUE;

}

}

} else {

unset($matches[$i]);

}

}

}

//Check to make sure we still have a closing

tag at the end

$body = implode(' ', $matches);

if(substr($body, -4) !="

$body = $body."

}

return $body;

} else {

return $string;

}

}

对我来说,以下工作:

$sentences = 2;

echo implode('. ', array_slice(explode('.', $string), 0, $sentences)) . '.';

这样可以确保它永远不会返回半字。

$short = substr($content, 0, 100);

$short = explode(' ', $short);

array_pop($short);

$short = implode(' ', $short);

print $short;

$summary = implode( ,array_pop(explode( , substr($content, 0,500)))); $afterSummary = implode( ,array_shift(explode( , substr($summary, 500))));谢谢

虽然我的代码注释无法解决问题,但您应该可以将其简化...

这是我在网上找到的另一个函数的修改;它会清除所有HTML,并首先清除一些时髦的MS字符;然后在内容中添加可选的省略号字符以表明它已被缩短。它会正确地分割成一个单词,因此您不会出现看似随机的字符;

/**

* Function to ellipse-ify text to a specific length

*

* @param string $text   The text to be ellipsified

* @param int    $max    The maximum number of characters (to the word) that should be allowed

* @param string $append The text to append to $text

* @return string The shortened text

* @author Brenley Dueck

* @link   http://www.brenelz.com/blog/2008/12/14/creating-an-ellipsis-in-php/

*/

function ellipsis($text, $max=100, $append='…') {

if (strlen($text) <= $max) return $text;

$replacements = array(

'|
|' => ' ',

'||' => ' ',

'||' => '\'',

'|‘|' => '\'',

'||' => '"',

'||' => '"',

);

$patterns = array_keys($replacements);

$replacements = array_values($replacements);

$text = preg_replace($patterns, $replacements, $text); // convert double newlines to spaces

$text = strip_tags($text); // remove any html.  we *only* want text

$out = substr($text, 0, $max);

if (strpos($text, ' ') === false) return $out.$append;

return preg_replace('/(\W)&(\W)/', '$1&$2', (preg_replace('/\W+$/', ' ', preg_replace('/\w+$/', '', $out)))) . $append;

}

输入:

The latest grocery news is that the Kroger Co. is testing a new self-checkout technology. My question is: Whats in it for me?

Kroger said the system, from Fujitsu,

输出:

The latest grocery news is that the Kroger Co. is testing a new self-checkout technology. My question is: What's in it for me? Kroger said the …

非常好。效果很好。感谢分享。

如果我是你,我会选择只选择第一句话。

$t='Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vestibulum justo eu leo.'; //input text

$fp=explode('. ',$t); //first phrase

echo $fp[0].'.'; //note I added the final ponctuation

这只会使事情变得繁琐。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值