Jonathan Toledo
Jonathan Toledo

Reputation: 359

Get text that is within brackets with single or double quotes

I try to found in my all PHP files the strings inside the i18n functions. Here is an example:

$string = '__("String 2"); __("String 3", __("String 4"));' . "__('String 5'); __('String 6', __('String 7'));";

var_dump(preg_match_all('#__\((\'|")([^\'"]+)(\'|")\)#', $string, $match));
var_dump($match);

I wanna get this result:

array
    0 => array
       0 => string 'String 2' (length=8)
       1 => string 'String 3' (length=8)
       2 => string 'String 4' (length=8)
       3 => string 'String 5' (length=8)
       4 => string 'String 6' (length=8)
       4 => string 'String 7' (length=8)

But unfortunately I get this result

array
    0 => array
        0 => string '__("esto es una prueba")' (length=24)
        1 => string '__("esto es una prueba 2")' (length=26)
        2 => string '__("prueba 4")' (length=14)
        3 => string '__('caca')' (length=10)
        4 => string '__('asdsnasdad')' (length=16)
    1  => array
        0 => string '"' (length=1)
        1 => string '"' (length=1)
        2 => string '"' (length=1)
        3 => string ''' (length=1)
        4 => string ''' (length=1)
    2 => array
       0 => string 'esto es una prueba' (length=18)
       1 => string 'esto es una prueba 2' (length=20)
       2 => string 'prueba 4' (length=8)
       3 => string 'caca' (length=4)
       4 => string 'asdsnasdad' (length=10)
    3 => array
       0 => string '"' (length=1)
       1 => string '"' (length=1)
       2 => string '"' (length=1)
       3 => string ''' (length=1)
       4 => string ''' (length=1)

Thanks in advance.

Upvotes: 1

Views: 612

Answers (2)

FailedDev
FailedDev

Reputation: 26940

preg_match_all('/(?<=\(["\']).*?(?=[\'"])/', $subject, $result, PREG_PATTERN_ORDER);
$result = $result[0];

Simple.

Note that I am using ( as an entry point to the match. If you have more exotic input you should provide it.

Upvotes: 1

Jason McCreary
Jason McCreary

Reputation: 73031

Don't capture the quotes.

preg_match_all('#__\([\'"]([^\'"]+)[\'"]\)#', $string, $match);

Also take a look at the flags parameter for preg_match_all() for different output formats.

Upvotes: 0

Related Questions