PHP-获取文本的前两句话?

PHP-获取文本的前两句话?,php,substring,Php,Substring,我的变量$content包含我的文本。我想从$content中创建一个摘录,并显示第一个句子,如果句子少于15个字符,我想显示第二个句子 我已经尝试过从文件中剥离前50个字符,它可以工作: <?php echo substr($content, 0, 50); ?> 但我对结果不满意(我不希望任何字眼被删掉) 是否有PHP函数获取整个单词/句子,而不仅仅是substr 非常感谢 有一个单词- 示例代码: <?php for ($i = 10; $i < 26; $

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

我已经尝试过从文件中剥离前50个字符,它可以工作:

<?php echo substr($content, 0, 50); ?>

但我对结果不满意(我不希望任何字眼被删掉)

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

非常感谢

有一个单词-

示例代码:

<?php

for ($i = 10; $i < 26; $i++) {
    $wrappedtext = wordwrap("Lorem ipsum dolor sit amet", $i, "\n");
    echo substr($wrappedtext, 0, strpos($wrappedtext, "\n")) . "\n";
}

这是一个从我在网上找到的另一个函数修改而来的函数;它去掉任何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='&hellip;') {
    if (strlen($text) <= $max) return $text;

    $replacements = array(
        '|<br /><br />|' => ' ',
        '|&nbsp;|' => ' ',
        '|&rsquo;|' => '\'',
        '|&lsquo;|' => '\'',
        '|&ldquo;|' => '"',
        '|&rdquo;|' => '"',
    );

    $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&amp;$2', (preg_replace('/\W+$/', ' ', preg_replace('/\w+$/', '', $out)))) . $append;
}
/**
*函数将文本椭圆化为特定长度
*
*@param string$text要省略的文本
*@param int$max应允许的最大字符数
*@param string$追加要追加到$text的文本
*@return-string缩短的文本
*@作者布伦利·杜克
*@linkhttp://www.brenelz.com/blog/2008/12/14/creating-an-ellipsis-in-php/
*/
函数省略号($text,$max=100,$append='&hellip;')){
如果(strlen($text)',
'| |' => ' ',
“|&rsquo;|”=>“\”,
“|&lsquo;|”=>“\”,
“|&ldquo;|”=>”,
“|&rdquo;|”=>“,
);
$patterns=数组_键($replacements);
$replacements=数组_值($replacements);
$text=preg_replace($patterns,$replacements,$text);//将双换行符转换为空格
$text=strip_tags($text);//删除任何html。我们*只*需要文本
$out=substr($text,0,$max);
if(strpos($text,')==false)返回$out。$append;
返回preg_replace('/(\W)&(\W)/','$1&;2',(preg_replace('/\W+$/','',preg_replace('/\W+$/','',out))。$append;
}
输入:

最新的食品杂货新闻是,克罗格公司正在测试一种新的自助结账技术。我的问题是:什么;是给我的吗

克罗格说,这套系统来自富士通,

输出:

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

最新的食品杂货新闻是克罗格公司正在测试一种新的自助结账技术。我的问题是:这对我有什么好处?克罗格说…

这将确保它不会返回半个字

$short = substr($content, 0, 100);
$short = explode(' ', $short);
array_pop($short);
$short = implode(' ', $short);
print $short;

我在我们的一个网站上写了一个函数来做类似的事情。我相信可以对它进行调整,以获得准确的结果

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

//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<$count;$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<$count;$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 <p> tag at the end
        $body = implode(' ', $matches);
        if(substr($body, -4) != "</p>") {
            $body = $body."</p>";
        }

        return $body; 
    } else {
        return $string;
    }
}
//此函数智能地将文本正文修剪为特定的长度
//字数多,但不会断句。
函数智能微调($string,$truncation){
$matches=preg_split(“/\s+/”,$string);
$count=计数($matches);
如果($count>$truncation){
//抓住最后一句话;我们需要确定
//这句话到底是不是结束了
$last_word=strip_标记($matches[$truncation-1]);
$lw_count=strlen($last_word);
//我们截断的最后一个单词有一个句子结尾
如果($last_word[$lw_count-1]==”“|$$last_word[$lw_count-1]==”?“|$$last_word[$lw_count-1]==”!”){

对于($i=$truncation;$i如果我是你,我会选择只选择第一句话

$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

这会使事情变得简单很多。

我想出来了,但很简单:

<?php
    $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
    }
?>

这是我编写的一个快速助手方法,用于获取给定正文的第一个
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));
}
函数摘要($body,$sentencesToDisplay=2){
$nakedBody=preg_replace('/\s+/','',strip_标签($body));
$SEQUENSIES=preg\u split('/(\.\124;\?\ 124;\!)(\ s)/',$nakedBody);
如果(计算($句子)$句子){
$stopAt+=strlen(句子);
如果($i>=$sentencesToDisplay-1)
打破
}
$stopAt+=($sentencesToDisplay*2);
返回修剪(substr($nakedBody,0,$stopAt));
}

我知道这是一篇老文章,但我也在寻找同样的东西

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

对我来说,以下几点起了作用:

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

(相关)。那里的解决方案会切断单词边界。
wordwrap
不会截断字符串,只是在某个位置插入换行符。
mb_strimwidth
会截断,但不遵守单词边界。是的,你是对的。。。很抱歉…但您可以执行类似substr($wrappedtext,0,strpos($wrappedtext,$delimiter)):)@仍然不遵守单词边界的Paul只是尝试了一下…它确实注意到了单词边界!您不能将true作为第四个参数传递…@Paul如果源字符串中的较早位置已经有换行符,则将失败。请尝试“Lorem\n ipsum dolor sit amet”“
wordwrap
确实遵守单词边界,但
strpos
不遵守。打断“我的名字是卢卡。我1953年1月1日出生在纽约。”=>“我的名字是卢卡。我出生在1。”@TomášFejfar在这种情况下,将
$dot=“.”“
更改为
$dot=“.”
(在句点后添加空格)作为旁注,如果您的感叹号没有被考虑,您可以执行
str_replace
以句点替换它们。
$content=str_replace(“!”,“.”,$content);
这些解决方案并非在所有情况下都有效。问号如何?当用户错误地说出字符串时,情况如何