I have this regex:
preg_match("/(comment|vid|nice)/i", $id)
And I want vid
part to match with video
or ivideo
.
What's the right way to add asterisks in vid
so it matches with those terms?
Surely there are many options for this, but one that comes to mind is
preg_match("/(comment|[\w-]*vid[\w-]*|nice)/i", $id)
whereas
\w
matches A-Z
, a-z
, 0-9
and _
-
simply matches -
[...]
is a character class, so it matches both 1. and 2.*
means matching 0 or more timesBtw you can fiddle with the matches by simply using an online tester like http://www.regextester.com.
You can use \p{L}*
where \p{L}
matches any lower- and uppercase letters and *
is a quantifier matching zero or more occurrences:
(comment|\p{L}*vid\p{L}*|nice)
See the regex demo and PHP demo:
$re = '/(comment|\p{L}*vid\p{L}*|nice)/';
$s = "new ivideo";
if (preg_match($re, $s, $m)) {
echo $m[0];
}
I would do
preg_match("/(comment|i?vid|nice)/i", $id)
The ?
makes the preceding i
optional.
Regex 101 demo: https://regex101.com/r/tK2iK2/1
PHP Demo: https://eval.in/494456
if(preg_match("/(comment|i?vid|nice)/i", 'video-player-5681ad0a08875')) {
echo 'It is a match';
} else {
echo 'It is not a match';
}