How to Extract Text within Parenthesis or Brackets in PHP?

There are many ways to extract text within parenthesis or brackets in PHP. However, the most straightforward and simple way is to use the preg_match() function.

This function takes two parameters: the first is a regular expression that defines the pattern you want to match, and the second is the string you want to search.

Some developers can use explode or strpos to expose positions of “(” and “)” symbols and then use substr to extract the content between them. However, this method is not foolproof as it can fail if there are nested parentheses or other symbols that might throw off the positions of the “(” and “)” symbols.

$text = 'Parenthesis can be used to add friendly comments or asides. They can also be used to (emphasize information) or to set off additional information that might otherwise be disruptive.';
preg_match('#\((.*?)\)#', $text, $matches);
print $matches[1];


$text = 'These [brackets] are used to indicate something is optional.';
preg_match('#\[(.*?)\]#', $text, $matches);
foreach ($matches as $key => $match) {
    print $match.'<br/>';
}

$text = '[Brackets] are often used to enclose text for [clarification] or as an aside.';
preg_match_all('#\[(.*?)\]#', $text, $matches);
print_r($matches);