How could this be done with regex?
return ( $s=='aa' || $s=='bb' || $s=='cc' || $s=='dd' ) ? 1 : 0;
I am trying:
$s = 'aa';
$result = preg_match( '/(aa|bb|cc|dd)/', $s );
echo $result; // 1
but obviously this returns 1
if $s
contains one or more of the specified strings (not when it is equal to one of them).
$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.
Use re. match() to check if a string matches a pattern re. match(pattern, string) tests if the regex pattern matches string . Use bool() on the returned match object to return a true or false value.
To check if a String matches a Pattern one should perform the following steps: Compile a String regular expression to a Pattern, using compile(String regex) API method of Pattern. Use matcher(CharSequence input) API method of Pattern to create a Matcher that will match the given String input against this pattern.
You need to use start ^
and end $
anchors to do an exact string match.
$result = preg_match( '/^(aa|bb|cc|dd)$/', $s );
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