-1

Is there a function that allows me to find the position of a word in a string? By position I don't mean which number char it is in a string. I know there are plenty of functions that do this already such as strpos() and strstr() and others. What I'm looking for is a function that will return the number a word is in string relative to the number of words.

So for example, if I'm searching for "string" in the text "This is a string" the result would be 4.

Note: I am not interested in splitting up the string into an array. I need a function that allows me to enter the string as a string, not as an array. Therefore the answer here Find the exact word position in string is not what I'm looking for.

Community
  • 1
  • 1
user1926567
  • 153
  • 1
  • 3
  • 8

2 Answers2

4

you could do:

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");
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
  • This worked. Is there a way to make this case in-sensitive? i.e, if I'm searching for "Test" it should return a match for both "Test" and "test". – user1926567 Sep 08 '13 at 07:58
  • @user1926567 yes, you can add strtolower() function as in updated answer above – Sudhir Bastakoti Sep 08 '13 at 08:01
  • Thanks again. I was thinking about the function strtolower() But wouldn't that convert it to lower case and then search only for the lower case (i.e, "test") and not the upper case (i.e, "Test") or would it search for both? Also is there a way I can contact you? To discuss a project? – user1926567 Sep 08 '13 at 08:06
  • @user1926567 it would search for both, because, we are doing strtolower() for both string and search text inside the function before preforming any kind of checks – Sudhir Bastakoti Sep 08 '13 at 08:07
2

you can explode string in array with space like

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

and use array_search for position

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

Also add +1 because array start from 0

hope this will sure solve your problem

liyakat
  • 11,825
  • 2
  • 40
  • 46
  • Thanks for reply, however I'm trying to do this without the need to split the string into an array. – user1926567 Sep 08 '13 at 06:16
  • welcome@user1926567, http://stackoverflow.com/questions/7077455/how-to-find-position-of-a-character-in-a-string-in-php use this one and pls i would be glad if you accept my answer. – liyakat Sep 08 '13 at 06:21