【问题标题】:php find word in string by char(letter) positionphp按字符(字母)位置在字符串中查找单词
【发布时间】:2015-09-11 11:48:10
【问题描述】:

有没有办法通过在字符串中找到一个字母的位置来找到字符串中的单词。我的意思是如果有任何简单的方法可以做到这一点。

我有一个字符串,例如 250 个字符和 70 个单词。我需要限制 div 中的字符串,所以我需要在 char 100 之前获取完整单词的整个字符串。

【问题讨论】:

  • 您能说得更具体些吗?提供示例字符串和所需的输出?例如,您的意思是字符串this is a test 和位置11 它将返回test
  • 你尝试了什么?
  • php的strrchr(string,char)函数你试过了吗
  • 我有一个字符串,例如 250 个字符和 70 个单词。我需要限制 div 中的字符串,所以我需要在 char 100 之前获取整个字符串单词。

标签: php string substring words


【解决方案1】:

不简单。你车用这个功能。

$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

【讨论】:

  • 非常感谢。这个功能也很好用。
【解决方案2】:

我有一个字符串,例如 250 个字符和 70 个单词。我需要 限制我的 div 中的字符串,所以我需要获取整个字符串单词 在 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

【讨论】:

  • 谢谢,虽然它不像我想的那么简单,但它得到了我需要的东西。
【解决方案3】:

这是最简单的答案:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-31
    相关资源
    最近更新 更多