我的变量$content包含我的文字.我想创建一个摘录$content并显示第一个句子,如果句子短于15个字符,我想显示第二个句子.
我已经尝试从文件中删除前50个字符,它的工作原理如下:
<?php echo substr($content, 0, 50); ?>
Run Code Online (Sandbox Code Playgroud)
但我对结果不满意(我不希望任何词语被削减).
是否有PHP函数获取整个单词/句子,而不仅仅是substr?
非常感谢!
ano*_*ous 13
我想通了,但它很简单:
<?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
}
?>
Run Code Online (Sandbox Code Playgroud)
这是我写的一个快速帮助方法,用于获取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));
}
Run Code Online (Sandbox Code Playgroud)
有一个单词 - wordwrap
示例代码:
<?php
for ($i = 10; $i < 26; $i++) {
$wrappedtext = wordwrap("Lorem ipsum dolor sit amet", $i, "\n");
echo substr($wrappedtext, 0, strpos($wrappedtext, "\n")) . "\n";
}
Run Code Online (Sandbox Code Playgroud)
输出:
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
Run Code Online (Sandbox Code Playgroud)
我知道这是一个旧帖子,但我一直在寻找同样的东西。
preg_match('/^([^.!?]*[\.!?]+){0,2}/', strip_tags($text), $abstract);
echo $abstract[0];
Run Code Online (Sandbox Code Playgroud)