I’m trying to figure if a string starts with the characters US, DS, UCS or DCS.
As tempting as it was to just do an unnecessarily long if statement, I figured there’s a better way, I’ve been trying to execute this using regular expressions but have had no joy:
$string = 'USQWERTY';
if(preg_match_all('|(US|DS|UCS|DCS)|', $string) // do something
It always returns false, I’m wondering if it’s because I haven’t used a wildcard? I’ve tried using *s after each word but haven’t had any joy with that either unfortunately.
Would really appreciate any advice on this, thanks!
First, you really don’t need preg_match_all, if what you want is one match. preg_match will be enough.
Second, if you use pipe symbol as a global pattern delimiter, you’ll have to escape it within the pattern itself. It’s easier just to choose the usual forward slash symbol. )
Finally, if you need to match only when the string begins (with the series of letters), you’ll have to alter the regex slightly:
Works for me in this example: