PHP - 获取文本的前两句话? [英] PHP - get first two sentences of a text?

查看:25
本文介绍了PHP - 获取文本的前两句话?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My variable $content contains my text. I want to create an excerpt from $content and display the first sentence and if the sentence is shorter than 15 characters, I would like to display the second sentence.

我已经尝试从文件中删除前 50 个字符,并且它有效:

I've already tried stripping first 50 characters from the file, and it works:

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

但我对结果不满意(我不想删减任何文字).

But I'm not happy with results (I don't want any words to be cut).

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

Is there a PHP function getting the whole words/sentences, not only substr?

非常感谢!

推荐答案

我想通了,虽然很简单:

I figured it out and it was pretty simple though:

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

这篇关于PHP - 获取文本的前两句话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆