請使用這樣的事情:
//$orgText = "This text is exactly the same length...";
//$orgText = "This text is shorter...";
//$orgText = "This_text_has_no_spaces_and_is_shorter";
//$orgText = "This_text_has_no_spaces_and_is_the_same";
//$orgText = "This_text_has_no_spaces_and_is_really_longer";
$orgText = "This text is longer and will be definitely cut but last word survives...";
$searchedWord = "This";
$charsToShow = 35;
$desiredExcerptLength = strlen($searchedWord) + $charsToShow;
$searchedWordPos = strpos($orgText, $searchedWord);
if ($searchedWordPos !== false) { // Word found
$subText = substr($orgText, $searchedWordPos); // Subtext: begins with searched word and ends at org text end
$subTextLength = strlen($subText);
if ($subTextLength > $desiredExcerptLength) { // Subtext longer than desired excerpt => cut it but keep last word
$spaceAfterLastWordPos = strpos($subText, ' ', $desiredExcerptLength);
$excerpt = substr($subText, 0, $spaceAfterLastWordPos ? $spaceAfterLastWordPos : $subTextLength);
}
else { // Subtext equal or shorter than desired excerpt => keep all text
$excerpt = $subText;
}
}
var_dump($excerpt);
很明顯的方式去做吧。
我希望這是你的意思。
你可以檢查一下:http://writecodeonline.com/php
有幾種文字的 「種」,您可以通過成:
Text中搜索詞不存在
=>返回NULL:
input: NULL, "", "Something without searched word"=> result: NULL
與空間比預期的摘錄長度較長的文本(搜索字長+例如35)
=>返回組織文本切出,但保持整個最後一個字:
"This text is longer and will be definitely cut but last word survives..." => "This text is longer and will be definitely"
用空格等於期望的摘錄長度的文本
=>返回的有機文本:
"This text is exactly the same length..." => "This text is exactly the same length..."
文本用空格比期望的摘錄長度短
=>返回的有機文本:
"This text is shorter..." => "This text is shorter..."
文本沒有空格長於期望的摘錄長度
=>返回的有機文本:
"This_text_has_no_spaces_and_is_really_longer" => "This_text_has_no_spaces_and_is_really_longer"
文本沒有空格等於期望的摘錄長度
=>返回組織文本:
"This_text_has_no_spaces_and_is_the_same" => "This_text_has_no_spaces_and_is_the_same"
文本沒有空格比預期的摘錄長度較短
=>返回組織文本:
"This_text_has_no_spaces_and_is_shorter" => "This_text_has_no_spaces_and_is_shorter"
那就是'substr'做,切東西,你告訴它。 – Prix 2014-09-04 06:00:25
什麼是電流輸出和所需的輸出? 「不工作」還不夠清楚。 – Sugar 2014-09-04 06:11:24
問題是輸出總是動態的! – OzzC 2014-09-04 06:17:10