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?
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.
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.
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.
Use a quantifier:
$pattern = "/do you want to eat ([a-z0-9]*) at my hometown\?/i";
// here __^
and escape the ?
==> \?
$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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With