PHP: Best way to extract text within parenthesis?

There are a few different ways to extract text within parentheses in PHP, depending on the specific requirements of your use case. One common approach is to use regular expressions to search for and match patterns of text that include parentheses. For example, you could use the preg_match() function to search for a pattern that includes an opening parenthesis, any number of characters, and a closing parenthesis.

Watch a course Learn object oriented PHP

Another option is to use the strpos() function to find the position of the open and close parenthesis and then use substr() function to extract the text within it.

Example:

<?php

$string = "This is a (test) string.";
$open = strpos($string, "(");
$close = strpos($string, ")");
$text = substr($string, $open+1, $close-$open-1);
echo $text;

This will output: "test"

You can also use the explode() function to split the string at the open parenthesis, and then use the reset() function to grab the first element of the resulting array, which will be the text before the open parenthesis. Then you can use another explode() function to split the first element of the array at the close parenthesis, and use the first element of the resulting array, which will be the text within the parentheses.

<?php

$string = "This is a (test) string.";
$parts = explode("(", $string);
$parts = explode(")", $parts[1]);
echo $parts[0];

This will output: "test"