After modifying a query result, I end up with an array like the following example:
[0] => foo (bar1)
[1] => bar (foo2)
[2] => bas
[3] => foo (bas3)
[4] => bar
As you can see, some of the values contain parentheses, some don’t.
I need the parentheses part of each value in an own (new) array. The key should be retained. If there are no parentheses in the value of the first array, the value in the second array should be
instead. The array keys in both arrays should be identical. The second array should therefore look like this:
[0] => (bar1)
[1] => (foo2)
[2] =>
[3] => (bas3)
[4] =>
Up to now I got this PHP code:
$pattern = "/((.*?))/"; //Looks for text in parentheses
$array1 = <see above>
$array2 = array(); //The second array, which should contain the extracted parentheses parts
foreach($array1 as $index => $value) {
$array2 = preg_grep($pattern,$array1);
}
This works fine, but it displays the whole value of $array1
as value in $array2
, when parentheses are found. Values in $array1
without parentheses are missing completely.
I cannot come up with a solution to only extract the (…)-part, remove it from $array1
and add
to $array2
if no parentheses are detected. I tried using preg_match to achieve this, but that gave me an array to string conversion error.
Does anyone have an idea how to get this problem solved?
5
Answers
You could use a regex on each element.
This will find an open parenthesis. followed by any characters until a closed parenthesis. When found, the first match will be returned else a
.This might help
A variant using
array_walk()
:The output obviously is:
With foreach and a formatted string:
I think most simply, this task is a good candidate for iterated calls of
strstr()
(strpbrk()
has the same functionality with a character mask). If the sought opening parenthesis is not found, fallback to the
.Code: (Demo)
As a deviation from Casimir’s
sscanf()
solution, I prefer to usearray_map()
and ignore the substring before the parentheses while parsing (using*
).Upon attempting to parse each string, the function will return a single-element array with either
null
, or the parenthetical value. Ifnull
fallback to the desired
string.In the parsing pattern,
%*[^(]
means match but do not retain characters from the start of the string to the first occurring opening parenthesis. Then the%s
will match and retain all subsequent non-whitespace characters. That retained parenthetical substring can be accessed as the first element insscanf()
‘s returned array.Code: (Demo)
The regex version of this is: (Demo)
Or with
preg_match()
: (Demo)