How to find full words only in string

前端 未结 5 1743
臣服心动
臣服心动 2020-12-21 00:44

How to find full words only in string



        
5条回答
  •  执笔经年
    2020-12-21 00:55

    Use the PHP function stripos().

    $str = "These aren't the droids you are looking for.";
    $search = "droids";
    $pos = stripos($str, $search);
    

    $pos will now be equal to 17, the position that the string starts at. If you are looking for the word to be of exactly the same case, then use the function strpos() instead; stripos() is case insensitive. If the function doesn't find the word, it will return FALSE.

    You can use that to determine whether a string contains a word.

    if(stripos($str, $search)){
        echo("It contains the word!");
    }else{
        echo("Word not found.");
    }
    

    If you want to check that it exists in the string by itself (not part of another word), then you should probably be looking at regular expressions. Something like:

    $str = "These aren't the droids you are looking for. This droid is.";
    $search = "droid";
    if (preg_match("/\b$search\b/", $str, $match)) {
        $result = $match[0];
    }
    

    This will match the index of this word, but not when it is used inside another word. So, in this example:

    $result == 51
    

    Even though the search term appeared earlier in the string.

    http://php.net/manual/en/function.strpos.php

提交回复
热议问题