php按字符(字母)位置查找字符串中的单词

php按字符(字母)位置查找字符串中的单词,php,string,substring,words,Php,String,Substring,Words,有没有办法通过让字母在字符串中的某个位置来查找字符串中的单词。我是说如果有什么简单的方法 例如,我有一个包含250个字符和70个单词的字符串。我需要限制div中的字符串,因此我需要在char 100之前获得包含完整单词的整个字符串。不简单。你可以使用这个功能 $string = "Hello world I use PHP"; $position = 7; function getWordFromStringInPosition ($string, $position) { if (s

有没有办法通过让字母在字符串中的某个位置来查找字符串中的单词。我是说如果有什么简单的方法


例如,我有一个包含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
$string=“Hello world我使用PHP”;
$position=7;
函数getWordFromStringInPosition($string,$position)
{
如果(strlen($string)==0)抛出新异常(“string为空”);
如果($position>strlen($string)|$position<0)抛出新异常(“位置在文本之外”);
$words=分解(“,$string);
$count=0;
foreach($words作为$word)
{
如果($position>$count&&$position<$count+strlen($word)+1)
{
返回$word;
}
其他的
{
$count+=strlen($word)+1;
}
}
}
echo getWordFromStringInPosition($string,$position);//世界

我有一个字符串,例如250个字符和70个单词。我需要 限制我的div中的字符串,因此我需要获得整个字符串 在char100之前

以下是我能拼凑出的一些小东西:

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
函数getPartialString($string,$max) { $words=explode(“”,$string); $i=0; $new_string=array(); foreach($k=>$word的单词) { $length=strlen($word); 如果($max<$length+$i+$k) { 打破 } $new_string[]=$word; $i+=$length; } 返回内爆(“”,$new_字符串); } echo getPartialString('这是一个测试',6);//这 echo getPartialString('这是一个测试',7);//这是
以下是最简单的答案:

substr($text, 0, strrpos(substr($text, 0, 100), " " ));

你能说得更具体些吗?提供一个示例字符串和所需的输出?例如,您的意思是使用string
这是一个测试,而position
11
它将返回
test
?您尝试了什么?您尝试过phpI的strrchr(string,char)函数了吗?例如,有250个字符和70个单词的字符串。我需要限制我的div中的字符串,所以我需要在char 100之前获得整个字符串。谢谢,虽然它不像我想的那么简单,但是它得到了我需要的。非常感谢。这个函数也非常有用。