Search code examples
phpregexstringpreg-matchcpu-word

Match whole word in a sentence that starts with specific letters


I'm tried to write PHP code for matching words by using letters, but my task is not satisfied by strpos(). I need to match the whole word which starts with the needle string.

$string = "How are you robin ?";
$searchletters = "yo";

Desired result: you


Solution

  • You can use this regex:

    $re = '/\b' . preg_quote($searchletters, '/') . '\w*\b/';
    
    preg_match($re, $string, $m);
    echo $m[0] . "\n";
    //=> you
    

    RegEx Demo