我正在尝试从PHP中的字符串中提取子字符串。提取的子字符串应以单词结尾。我尝试了以下代码,但没有得到任何输出。
if (strlen($userresult->aboutme) > 20) // value of $userresult->aboutme is 'Very cool and friendly'
{
$description=substr($userresult->aboutme, 0, strpos($userresult->aboutme, ' ', 20));
}
else
{
$description=$userresult->aboutme;
}
echo $description; // not outputting any result
我希望子字符串以一个单词结尾。这里,我希望输出为Very cool and friendly
,而不是Very cool and friend
,这是我们尝试使用substr($userresult->aboutme, 0, 20);
时的输出。我做错了什么?有人能帮我解决这个问题吗?
提前谢谢。
您使用的是strpos((,它从字符串的开头开始查找。您想要strRpos()
(r=reverse(:
$description=substr($userresult->aboutme, 0, strrpos($userresult->aboutme, ' '));
您不希望使用strpos()
的偏移量,因为在这种情况下它可能会起作用,但如果前几个单词更短/更长,它就不再起作用。
// split in words
$words = explode(' ', $userresult->aboutme);
// remove the last word
array_pop($words);
// combine again
echo implode(' ', $words);
这不尊重任何其他分隔符作为逗号或点。但你也没有这么做。
像这样使用
if (strlen($userresult->aboutme) > 15) // value of $userresult->aboutme is 'Very cool and friendly'
{
$description=substr($userresult->aboutme, 0, strrpos($userresult->aboutme, ' '));
}
else
{
$description=$userresult->aboutme;
}
echo $description;