This tutorial will discuss how to check if string contains brackets in PHP.
To check if a string contains brackets in PHP, we can utilize regular expressions. The regular expression pattern that should match a string that contains both opening and closing brackets in the correct order is as follows,
'/(S*)|[S*]|{S*}/'
We can pass this regex pattern and the string value to the preg_match() function. If the string contains both opening and closing brackets in the correct order, the function will return 1, indicating a match.
We have created a separate function,
function hasBrackets($strValue) { return preg_match('/(S*)|[S*]|{S*}/', $strValue) === 1; }
It accepts a string as an argument and returns true if the given string contains both opening and closing brackets in the correct order.
Let’s see the complete example,
<?php /** * Check if a string contains brackets. * * @param string $strValue The string to validate. * @return bool True if the string contains brackets, false otherwise. */ function hasBrackets($strValue) { return preg_match('/(S*)|[S*]|{S*}/', $strValue) === 1; } $strValue = 'This random text which (contains) brackets for [testing]'; if (hasBrackets($strValue)) { echo "The string contains brackets."; } else { echo "The string does not contain brackets."; } ?>
Output
Frequently Asked:
The string contains brackets.
Summary
Today, we learned how to check if string contains brackets in PHP.