【问题标题】:Find the Position of a Word in a String? [duplicate]在字符串中查找单词的位置? [复制]
【发布时间】:2013-09-08 16:02:04
【问题描述】:

有没有一个函数可以让我找到一个单词在字符串中的位置?位置我不是指它在字符串中的哪个数字字符。我知道已经有很多函数可以做到这一点,例如 strpos() 和 strstr() 等。我正在寻找的是一个函数,它将返回一个单词在字符串中相对于单词数的数字。

例如,如果我在文本“This is a string”中搜索“string”,结果将是 4。

注意:我对将字符串拆分为数组不感兴趣。我需要一个允许我将字符串作为字符串而不是数组输入的函数。因此Find the exact word position in string 的答案不是我想要的。

【问题讨论】:

  • 所有“单词”都用空格隔开吗?
  • 是的,所有单词都用空格隔开。
  • So for example, if I'm searching for "string" in the text "This is a string" the result would be 4.这是什么4?
  • @itachi "4" 是字符串中的第 4 个单词。
  • @hjpotter92 这个答案对我没有帮助。

标签: php


【解决方案1】:

你可以这样做:

function find_word_pos($string, $word) {
    //case in-sensitive
    $string = strtolower($string); //make the string lowercase
    $word = strtolower($word);//make the search string lowercase
    $exp = explode(" ", $string);
    if (in_array($word, $exp)) { 
        return array_search($word, $exp) + 1;
    }
    return -1; //return -1 if not found
}
$str = "This is a string";
echo find_word_pos($str, "string");

【讨论】:

  • 这行得通。有没有办法让这种情况不敏感?即,如果我正在搜索“Test”,它应该返回“Test”和“test”的匹配项。
  • @user1926567 是的,您可以按照上面更新的答案添加 strtolower() 函数
  • 再次感谢。我在考虑函数 strtolower() 但不是将其转换为小写然后只搜索小写(即“test”)而不是大写(即“Test”)还是会搜索对彼此而言?还有有什么方法可以联系你吗?讨论一个项目?
  • @user1926567 它会同时搜索两者,因为在执行任何类型的检查之前,我们正在函数内对字符串和搜索文本执行 strtolower()
【解决方案2】:

你可以explode 数组中的字符串,如

    $arr_str = explode(" ","This is a string")

并使用array_search 定位

    echo array_search("string",$arr_str)+1;

还要加上+1,因为数组从0开始

希望这一定能解决您的问题

【讨论】:

  • 感谢您的回复,但是我正在尝试这样做,而无需将字符串拆分为数组。
  • welcome@user1926567, stackoverflow.com/questions/7077455/… 使用这个,如果你接受我的回答,我会很高兴。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-21
  • 1970-01-01
  • 1970-01-01
  • 2019-05-31
  • 1970-01-01
相关资源
最近更新 更多