Reputation:
I am doing the following:
$text = 'L\' utente _{nickname} ti ha invitato a giocare';
$text_vars = preg_match('#\_{(.*?)\}#', $text, $matches);
returns:
Array
(
[0] => _{nickname}
[1] => nickname
)
How can it be made to only return the following?
Array
(
[0] => nickname
)
Upvotes: 5
Views: 23154
Reputation: 127
try this
$text = 'L\' utente _{nickname} ti ha invitato a giocare';
$text_vars = preg_match('#\_{(.*?)\}#', $text, $matches) ? $matches[1] : '';
echo $text_vars;
Upvotes: 9
Reputation: 89557
You can use a lookahead (?=..)
and a lookbehind (?<=..)
(or a match reset \K
)
$text_vars = preg_match('~(?<=_{)[^}]++(?=})~', $text, $match);
Or
$text_vars = preg_match('~_{\K[^}]++(?=})~', $text, $match);
Upvotes: 1
Reputation: 80639
From preg_match()
documentation:
If
matches
is provided, then it is filled with the results of search.$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.
For the desired behavior, use array_shift()
like this:
$text = 'L\' utente _{nickname} ti ha invitato a giocare';
$text_vars = preg_match('#\_{(.*?)\}#', $text, $matches);
$temp = array_shift( $matches );
Upvotes: 11