Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match any word in a String with Regex in PHP

I have these strings. I want a regular expression to match them and return true when I pass them to preg_match function.

do you want to eat katak at my hometown?
do you want to eat teloq at my hometown?
do you want to eat tempeyek at my hometown?
do you want to eat karipap at my hometown?

How do I create a pattern in regex that will match the above pattern? Like this:

do you want to eat * at my hometown?

Asterik (*) means any word. Here is the regex pattern that I have so far:

$text = "do you want to eat meatball at my hometown?";
$pattern = "/do you want to eat ([a-zA-Z0-9]) at my hometown?/i";

if (preg_match($pattern, $text)) {
    echo "A match was found.";
} else {
    echo "A match was not found.";
}

The ([a-zA-Z0-9]) format is not matching on word. How do I match a string on a word?

like image 425
user3160596 Avatar asked Jan 04 '14 15:01

user3160596


People also ask

How do you search for a word in regex?

To run a “whole words only” search using a regular expression, simply place the word between two word boundaries, as we did with ‹ \bcat\b ›. The first ‹ \b › requires the ‹ c › to occur at the very start of the string, or after a nonword character.

How do you check if a string matches a regex in PHP?

In PHP, you can use the preg_match() function to test whether a regular expression matches a specific string. Note that this function stops after the first match, so this is best suited for testing a regular expression more than extracting data.

How do I match a string in PHP?

Answer: Use the PHP strcmp() function You can use the PHP strcmp() function to easily compare two strings. This function takes two strings str1 and str2 as parameters. The strcmp() function returns < 0 if str1 is less than str2 ; returns > 0 if str1 is greater than str2 , and 0 if they are equal.


2 Answers

Use a quantifier:

$pattern = "/do you want to eat ([a-z0-9]*) at my hometown\?/i";
//                                here __^

and escape the ? ==> \?

like image 92
Toto Avatar answered Nov 05 '22 18:11

Toto


$text = "do you want to eat meatball at my hometown?";
$pattern = "/(\w+)(?=\sat)/";
if (preg_match($pattern, $text))

(\w+) matches one or more word characters.

(?=\sat) is a positive lookahead that matches one whitespace \s and the letters at.

Regex live demo

like image 30
revo Avatar answered Nov 05 '22 18:11

revo