Albeis
Albeis

Reputation: 1580

PHP regex to extract both open parenthesis and the following text

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!

Upvotes: 0

Views: 56

Answers (2)

The fourth bird
The fourth bird

Reputation: 163277

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
)

Upvotes: 1

user3783243
user3783243

Reputation: 5224

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.

Upvotes: 1

Related Questions