How to find full words only in string

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

How to find full words only in string



        
5条回答
  •  离开以前
    2020-12-21 01:03

    To see if a particular word is in a string, you can use a regular expression with word boundaries, like so:

    $str = "By ILI LIKUALAYANA MOKHTAKUALAR AND G. SURACH Datuk Dr Hasan Ali says he has no intention of joining Umno. Pic by Afendi Mohamed KUALA LUMPUR: FORMER Selangor Pas commissioner Datuk Dr Hasan Ali has not ruled out the possibility of returning to Pas' fold";
    $search = "KUALA";
    
    if (preg_match("/\b$search\b/", $str)) {
        // word found
    }
    

    Here \b means "boundary of a word". It doesn't actually match any characters, just boundaries, so it matches the edge between words and spaces, and also matches the edges at the ends of the strings.

    If you need to make it case-insensitive, you can add i to the end of the match string like this: "/\b$search\b/i".

    If you need to know where in the string the result was, you can add a third $matches parameter which gives details about the match, like this:

    if (preg_match("/\b$search\b/", $str, $matches)) {
        // word found
        $position = $matches[1];
    }
    

提交回复
热议问题