Regex match words PHP

Words match

This regular expression can be used to validate that a given string contains only characters in it or extract two words from a given string.

Simple word match

The regular expression to match only words looks like this (including compound words):

"/^\\b(?:\\w|-)+\\b$/"

Test it!
This is some text inside of a div block.

True

False

Enter a text in the input above to see the result

Example code in PHP:

// Validate word
$words_regex = "/^\\b(?:\\w|-)+\\b$/"; 
echo preg_match($words_regex, 'word'); // returns 1
echo preg_match($words_regex, 'pet-friendly'); // returns 1
echo preg_match($words_regex, 'not a word'); // returns 0

// Extract words from a string
$extract_words_pattern = "/\\b(?:\\w|-)+\\b/";
$string_to_match = 'Hello, world!';
preg_match_all($extract_words_pattern, $string_to_match, $matches);
print_r($matches[0])// matches[0] is ['Hello', 'world']
Test it!
This is some text inside of a div block.

True

False

Enter a text in the input above to see the result

Test it!
This is some text inside of a div block.

True

False

Enter a text in the input above to see the result