Regex to match specific functions and their arguments in files

前端 未结 6 1795
没有蜡笔的小新
没有蜡笔的小新 2021-01-16 07:33

I\'m working on a gettext javascript parser and I\'m stuck on the parsing regex.

I need to catch every argument passed to a specific method call _n( and

6条回答
  •  迷失自我
    2021-01-16 07:53

    One bit of code (you can test this PHP code at http://writecodeonline.com/php/ to check):

    $string = '_("foo")
    _n("bar", "baz", 42); 
    _n(domain, "bux", var);
    _( "one (optional)" );
    apples === 0 ? _( "No apples" ) : _n("%1 apple", "%1 apples", apples)';
    
    preg_match_all('/(?<=(_\()|(_n\())[\w", ()%]+(?=\))/i', $string, $matches);
    
    foreach($matches[0] as $test){
        $opArr = explode(',', $test);
        foreach($opArr as $test2){
           echo trim($test2) . "\n";
           }
        }
    

    you can see the initial pattern and how it works here: http://regex101.com/r/fR7eU2/1

    Output is:

    "foo"
    "bar"
    "baz"
    42
    domain
    "bux"
    var
    "one (optional)"
    "No apples"
    "%1 apple"
    "%1 apples"
    apples
    

提交回复
热议问题