php 按字符(字母)位置在字符串中查找单词
php find word in string by char(letter) position
有没有什么方法可以通过字符串中某个字母的位置来查找字符串中的单词。我的意思是,如果有任何简单的方法可以做到这一点。
例如,我有一个包含 250 个字符和 70 个单词的字符串。我需要限制 div 中的字符串,所以我需要在 char 100.
之前获取包含完整单词的整个字符串
不简单。你的车用这个功能。
$string = "Hello world I use PHP";
$position = 7;
function getWordFromStringInPosition ($string, $position)
{
if (strlen($string) == 0) throw new Exception("String is empty.");
if ($position > strlen($string) || $position < 0) throw new Exception("The position is outside of the text");
$words = explode(" ", $string);
$count = 0;
foreach ($words as $word)
{
if ($position > $count && $position < $count + strlen($word) + 1)
{
return $word;
}
else
{
$count += strlen($word) + 1;
}
}
}
echo getWordFromStringInPosition ($string, $position); // world
I have a string by for example 250 chars and 70 words. I would need to
limit the string in my div so I need to get the whole string words
before char 100.
这是我能够拼凑的一些东西:
function getPartialString($string, $max)
{
$words = explode(' ', $string);
$i = 0;
$new_string = array();
foreach ($words as $k => $word)
{
$length = strlen($word);
if ($max < $length + $i + $k)
{
break;
}
$new_string[] = $word;
$i += $length;
}
return implode(' ', $new_string);
}
echo getPartialString('this is a test', 6); // this
echo getPartialString('this is a test', 7); // this is
这是最简单的答案:
substr($text, 0, strrpos(substr($text, 0, 100), " " ));
有没有什么方法可以通过字符串中某个字母的位置来查找字符串中的单词。我的意思是,如果有任何简单的方法可以做到这一点。
例如,我有一个包含 250 个字符和 70 个单词的字符串。我需要限制 div 中的字符串,所以我需要在 char 100.
之前获取包含完整单词的整个字符串不简单。你的车用这个功能。
$string = "Hello world I use PHP";
$position = 7;
function getWordFromStringInPosition ($string, $position)
{
if (strlen($string) == 0) throw new Exception("String is empty.");
if ($position > strlen($string) || $position < 0) throw new Exception("The position is outside of the text");
$words = explode(" ", $string);
$count = 0;
foreach ($words as $word)
{
if ($position > $count && $position < $count + strlen($word) + 1)
{
return $word;
}
else
{
$count += strlen($word) + 1;
}
}
}
echo getWordFromStringInPosition ($string, $position); // world
I have a string by for example 250 chars and 70 words. I would need to limit the string in my div so I need to get the whole string words before char 100.
这是我能够拼凑的一些东西:
function getPartialString($string, $max)
{
$words = explode(' ', $string);
$i = 0;
$new_string = array();
foreach ($words as $k => $word)
{
$length = strlen($word);
if ($max < $length + $i + $k)
{
break;
}
$new_string[] = $word;
$i += $length;
}
return implode(' ', $new_string);
}
echo getPartialString('this is a test', 6); // this
echo getPartialString('this is a test', 7); // this is
这是最简单的答案:
substr($text, 0, strrpos(substr($text, 0, 100), " " ));