php-regexHow to use PHP regex to match a boolean value?
PHP regex can be used to match a boolean value by using the preg_match()
function. This function takes two parameters, the first being the regular expression pattern and the second being the string to match against.
$string = 'true';
$pattern = '/^(true|false)$/';
if (preg_match($pattern, $string)) {
echo 'Matched';
} else {
echo 'Not matched';
}
Output example
Matched
The code above uses the preg_match()
function to match a boolean value. The first parameter is the regular expression pattern /^(true|false)$/
which looks for either the string true
or false
at the beginning and end of the string. The second parameter is the string to match against, in this case true
. If the string matches the pattern, the preg_match()
function will return true
and the Matched
string will be printed. Otherwise, the Not matched
string will be printed.
Helpful links
More of Php Regex
- How to get last matched occurrence in PHP regex?
- How to use PHP regex to match a zip code?
- How to convert a PHP regex to JavaScript regex?
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex to match special characters?
- How to use PHP regex to match an exact string?
- How to use PHP regex to match an XML tag?
- How to get the first match when using regex in PHP?
- How to use PHP regex to match a year?
- How to match a space using PHP regex?
See more codes...