I need some help writing a function. If a string has some text in parentheses, I need to split it into two separate variables: one containing only the text in parentheses and one containing everything before the parentheses.
Here’s the pseudo-code:
if ($variable1 has text in parentheses) {
$variable2 = only what is in parentheses;
$variable1 = everything before the space and text in parentheses;
}
So, for example, if “Death Magnetic (Metallica)” was the string, the two variables would contain “Death Magnetic” and “Metallica”.
Any help would be greatly appreciated 
$string = "Death Magnetic (Metallica)";
$position = strpos($string, '(');
if ($position !== false) {
$before = substr($string, 0, $position - 1);
$after = substr($string, $position + 1, strlen($string) - $position - 2);
}
echo $string . "<br />";
echo $before . "<br />";
echo $after . "<br />";
Death Magnetic (Metallica)
Death Magnetic
Metallica
http://php.net/manual/en/function.strpos.php
http://php.net/manual/en/function.substr.php
http://php.net/manual/en/function.strlen.php
http://php.net/manual/en/function.explode.php
Thanks for sharing this. I will save it. I am starting to learn HTML gradually.
Thank you very much.
I didn’t even think of using the string position, I was attempting to come up with an expression (which I suck at).
If you prefer to use a regular expression you can:
$string = "Death Magnetic (Metallica)";
preg_match("#(.*) \\((.*)\\)#", $string, $matches);
print_r($matches);
Array
(
[0] => Death Magnetic (Metallica)
[1] => Death Magnetic
[2] => Metallica
)
the regular expression’s way is too simple,but i don’t understand this line’s meaning.
preg_match("#(.*) \\((.*)\\)#", $string, $matches);
preg_match("#(.*) \\((.*)\\)#", $string, $matches);
Here ‘#’ is a delimiter.
and (.) followed by a ‘#’ will match everything before the character ‘(’.
and the second (.) will matches the characters before the close parentheses.
In regular expression parentheses is used to represent grouping.
So if we want to match literal parentheses then we need to escape that one.
So in the above expression we escaped the parentheses like,’ \(’