I'm trying to detect initial open parenthesis on the incoming word and if so, extract also the text preceding.
For instance:
One possible incoming word could be:
(original
The idea is to have on the one hand the open parenthesis
"("
and on the other hand
"original"
This is what I currently have:
preg_match('/(\()(\w )/', $input_line, $output_array);
which match in this way:
array(3
0 => (original
1 => (
2 => original
)
I'm struggling with making it return something like:
array(2
0 => (
1 => original
)
I know that it can be done using strpos
and from there split, but furthermore, it won't be only the open parenthesis but curly braces, etc... so regex should match several chars.
What I'm missing? Thanks!
CodePudding user response:
The 0
index is the full matched pattern. Each indice after that is a capture group.
https://www.php.net/manual/en/function.preg-match.php
$matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on.
CodePudding user response:
You can get the output that you want changing the pattern to using a capture group in a positive lookahead for the \w
, and match the (
preg_match('/\((?=(\w ))/', "(original", $output_array);
print_r($output_array);
Output
Array
(
[0] => (
[1] => original
)