Safy
Safy

Reputation: 37

php regex : extract functions paramerts from code files

i want to fetch all my wordpress plugin then get all gettext functions parameters

Example

 die(_e('Error')) ;
 die( '<b>'._e('Error').'</b>' ) ;
 _e('Error')

function for wordpress gettext i used

_e , __

and how to bypass similar functions

use_e , get_email , select__


I created this function by regex but it's not very useful

$list_words = array();

function po_fetch_code($dir , $preg = "/_\(('|\")(.*?)('|\")\)/"){
     if( is_dir($dir) ){
           $list = scandir($dir) ;
           foreach($list as $l){
              if($l == '.' || $l == '..'){
                // Do Nothing
              }else{
                po_fetch_code($dir.'/'.$l , $preg) ;
              }

           }
     }else{
          $ext = strrchr($dir , '.') ;
          //if($ext == '.php' || $ext == '.html' || $ext == 'html'){
               //$cont = file_get_contents($dir) ;
               $list = file($dir) ;
               global $list_words ;
               foreach($list as $key => $l){
                  preg_match_all( $preg , $l , $matches );
                  if(!empty($matches[2])){
                        foreach($matches[2] as $k=>$m){
                                 //$m = str_replace(array( "\'",'\\' , '"' , "'",'\'' ), '' ,$m) ;
                                 //$m = str_replace('\'s', 's' ,$m) ;
                                 if(!isset($list_words[$m])){
                                     $list_words[$m]['msgid'] = array($m) ;
                                     $list_words[$m]['msgstr'] = array($m) ;
                                     $list_words[$m]['reference'] = array() ;
                                  }
                                  $list_words[$m]['reference'][] = $dir.':'.$key ;
                        }
                  }
               }

         // }
     }
}

$dir = 'themes/mytheme/' ;
po_fetch_code($dir , "/__\(('|\")(.*?)('|\")\)/" ) ;
po_fetch_code($dir , "/_e\(('|\")(.*?)('|\")\)/" ) ;

Is there's any way to enhance my function ?? Thanks

Upvotes: 0

Views: 89

Answers (1)

lxg
lxg

Reputation: 13117

If your goal is to generate a translation catalog of your theme, you should use the xgettext command line tool. There is really no sense in trying to parse PHP files manually.

## first, collect all the theme’s PHP files into one temporary file
find -name "*.php" wp-content/themes/yourtheme > /tmp/themefiles.txt

# create catalog from translatable strings in your theme’s files
xgettext --from-code=utf-8 --keyword=__ --keyword=_e --keyword="_n:1,2" --keyword="_x:2c,1" --language=PHP -j -o wp-content/themes/yourtheme/yourtheme.pot -f /tmp/themefiles.txt

If you don’t have access to a Linux shell on your webserver, you can set up a Linux VM with a simple distro like Ubuntu or Mint and do the xgettext stuff there.

Upvotes: 2

Related Questions