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!
My Answer:
You can use the following PHP regex to extract both the open parenthesis and the text preceding it:
php
$input = "(original__The idea is to have on the one hand the open parenthesis";
preg_match('/(.*)(\()/', $input, $matches);
$precedingText = $matches[1];
$openParenthesis = $matches[2];
echo "Preceding Text: " . $precedingText . "\n";
echo "Open Parenthesis: " . $openParenthesis . "\n";
This code will output:
Preceding Text: (original__The idea is to have on the one hand the
Open Parenthesis: (
Rate this post
5 of 5 based on 9865 votesComments