Search code examples
phpstringpreg-match

Find whole word at beginning of string with preg_match?


I am trying to find whole words e.g. 'Location:', 'Contact:', at the beginning of a string with preg_match.

Please could someone provide and quick example.


Solution

  • starts (^) with word character (\w) and has one or more of them (+) and should be captured and stored in $matches (brackets)

    $in = "First word is captured";
    preg_match("/^(\w+)/",$in,$matches);
    echo $matches[1];