确保 PHP substr 在单词而不是字符上完成
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1233290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Making sure PHP substr finishes on a word not a character
提问by Cool Hand Luke
I know how to use the substr function but this will happy end a string halfway through a word. I want the string to end at the end of a word how would I go about doing this? Would it involve regular expression? Any help very much appreciated.
我知道如何使用 substr 函数,但这会很高兴在一个单词的中途结束一个字符串。我希望字符串在一个词的末尾结束,我该怎么做?它会涉及正则表达式吗?非常感谢任何帮助。
This is what I have so far. Just the SubStr...
这是我到目前为止。只是 SubStr ...
echo substr("$body",0,260);
Cheers
干杯
回答by Achshar
substr($body, 0, strpos($body, ' ', 260))
回答by Paul Dixon
It could be done with a regex, something like this will get up to 260 characters from the start of string up to a word boundary:
可以用正则表达式来完成,这样的事情将从字符串的开头到单词边界最多 260 个字符:
$line=$body;
if (preg_match('/^.{1,260}\b/s', $body, $match))
{
$line=$match[0];
}
Alternatively, you could maybe use the wordwrapfunction to break your $body into lines, then just extract the first line.
或者,您可以使用wordwrap函数将您的 $body 分成几行,然后提取第一行。
回答by Zed
You can try this:
你可以试试这个:
$s = substr($string, 0, 261);
$result = substr($s, 0, strrpos($s, ' '));
回答by Gumbo
You could do this: Find the first space from the 260th character on and use that as the crop mark:
您可以这样做:从第 260 个字符开始找到第一个空格并将其用作裁剪标记:
$pos = strpos($body, ' ', 260);
if ($pos !== false) {
echo substr($body, 0, $pos);
}
回答by Oleksandr Knyga
I use this solution:
我使用这个解决方案:
$maxlength = 50;
substr($name, 0, ($spos = strpos($name, ' ', $lcount = count($name) > $maxlength ? $lcount : $maxlength)) ? $spos : $lcount );
Or inline:
或内联:
substr($name, 0, ($spos = strpos($name, ' ', $lcount = count($name) > 50 ? $lcount : 50)) ? $spos : $lcount );
回答by Sanne
function substr_word($body,$maxlength){
if (strlen($body)<$maxlength) return $body;
$body = substr($body, 0, $maxlength);
$rpos = strrpos($body,' ');
if ($rpos>0) $body = substr($body, 0, $rpos);
return $body;
}
回答by Batbekh Batmagnai
wordwrap and explode then first array element is you want
$wr=wordwrap($text,20,':');
$strs=explode(":",$wr);
$strs[0]
自动换行和爆炸然后第一个数组元素是你想要的
$wr=wordwrap($text,20,':');
$strs=explode(":",$wr);
$strs[0]
回答by Ivan Proskuryakov
What about this?
那这个呢?
/**
* @param string $text
* @param int $limit
* @return string
*/
public function extractUncutPhrase($text, $limit)
{
$delimiters = [',',' '];
$marks = ['!','?','.'];
$phrase = substr($text, 0, $limit);
$nextSymbol = substr($text, $limit, 1);
// Equal to original
if ($phrase == $text) {
return $phrase;
}
// If ends with delimiter
if (in_array($nextSymbol, $delimiters)) {
return $phrase;
}
// If ends with mark
if (in_array($nextSymbol, $marks)) {
return $phrase.$nextSymbol;
}
$parts = explode(' ', $phrase);
array_pop($parts);
return implode(' ', $parts); // Additioanally you may add ' ...' here.
}
Tests:
测试:
public function testExtractUncutPhrase()
{
$stringUtils = new StringUtils();
$text = 'infant ton-gue could make of both names nothing';
$phrase = 'infant';
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 11));
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 12));
$text = 'infant tongue5';
$phrase = 'infant';
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 13));
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 11));
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 7));
}
public function testExtractUncutPhraseEndsWithDelimiter()
{
$stringUtils = new StringUtils();
$text = 'infant tongue ';
$phrase = 'infant tongue';
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 13));
$text = 'infant tongue,';
$phrase = 'infant tongue';
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 13));
}
public function testExtractUncutPhraseIsSentence()
{
$stringUtils = new StringUtils();
$text = 'infant tongue!';
$phrase = 'infant tongue!';
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 14));
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 100));
$text = 'infant tongue!';
$phrase = 'infant tongue!';
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 13));
$text = 'infant tongue.';
$phrase = 'infant tongue.';
$this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 13));
}
回答by andres descalzo
$pos = strpos($body, $wordfind);
echo substr($body,0, (($pos)?$pos:260));
回答by vijay
public function Strip_text($data, $size, $lastString = ""){
$data = strip_tags($data);
if(mb_strlen($data, 'utf-8') > $size){
$result = mb_substr($data,0,mb_strpos($data,' ',$size,'utf-8'),'utf-8');
if(mb_strlen($result, 'utf-8') <= 0){
$result = mb_substr($data,0,$size,'utf-8');
$result = mb_substr($result, 0, mb_strrpos($result, ' ','utf-8'),'utf-8');;
}
if(strlen($lastString) > 0) {
$result .= $lastString;
}
}else{
$result = $data;
}
return $result;
}
Pass the string into funtion Strip_text("Long text with html tag or without html tag", 15)Then this function will return the first 15 character from the html string without html tags. When string less than 15 character then return the full string other wise it will return the 15 character with $lastString parameter string.
将字符串传入函数Strip_text("Long text with html tag or without html tag", 15)然后该函数将返回不带 html 标签的 html 字符串的前 15 个字符。当字符串小于 15 个字符时,则返回完整字符串,否则它将返回 15 个字符和 $lastString 参数字符串。
Example:
例子:
Strip_text("<p>vijayDhanasekaran</p>", 5)
Result: vijay
结果:维杰
Strip_text("<h1>vijayDhanasekaran<h1>",5,"***....")
Result: vijay***....
结果:vijay***....

