Daniel
Daniel

Reputation: 305

Replace variable texts with regular expressions

I'm reformulating one of my old programs and using TextCrawler to automate text replacements in several code files, but I'm struggling to make the following change:

I need to find all 'text' functions (example):

$object->text('TRANSLATE_KEY_A')
$object->text('TRANSLATE_KEY_B')
...

and replace them with (example):

__('RETURNED_TEXT_FROM_TRANSLATE_KEY_A', TEXT_DOMAIN)
__('RETURNED_TEXT_FROM_TRANSLATE_KEY_B', TEXT_DOMAIN)
...

Where RETURNED_TEXT_FROM_TRANSLATE_KEY_X are set with the 'text' array's key in another code file

array_push($text, array('key' => 'TRANSLATE_KEY_A',
                        'extras' => '',
                        'text' => 'Translated Text A'));

array_push($text, array('key' => 'TRANSLATE_KEY_B',
                        'extras' => '',
                        'text' => 'Translated Text B'));

The final result should be:

$object->text('TRANSLATE_KEY_A')
$object->text('TRANSLATE_KEY_B')
...

replaced with

__('Translated Text A', TEXT_DOMAIN)
__('Translated Text B', TEXT_DOMAIN)
...

There are over 1500 of these :( Is it possible to achieve this with regular expression in TextCrawler, and how? Or any other idea? Thanks

Upvotes: 0

Views: 61

Answers (1)

speakr
speakr

Reputation: 4209

If you want to use a php array to provide the replacement data it is probably best to just use php itself for the task.

Example script.php:

// your $text array
$text = array();
array_push($text, array(
    'key' => 'TRANSLATE_KEY_A',
    'extras' => '',
    'text' => 'Translated Text A')
);
array_push($text, array(
    'key' => 'TRANSLATE_KEY_B',
    'extras' => '',
    'text' => 'Translated Text B')
);
...

// create a separate array from your $text array for easy lookup
$data_arr = array();
foreach ($text as $val) {
    $data_arr[$val['key']] = $val['text'];
}

// your code file, passed as first argument
$your_code_file = $argv[1];

// open file for reading
$fh = fopen($your_code_file, "r");
if ($fh) {
    while (($line = fgets($fh)) !== false) {
        // check if $line has a 'text' function and if the key is in $data_arr
        // if so, replace $line with the __(...) pattern
        if (preg_match('/^\$object->text\(\'([^\']+)\'\)$/', $line, $matches)
            && isset($data_arr[$matches[1]])) {
            printf("__('%s', TEXT_DOMAIN)\n", $data_arr[$1]);
        } else {
            print($line);
        }
    }
    fclose($fh);
} else {
    print("error while opening file\n");
}

Call:

php script.php your_code_file

Just add functionality to iterate over all of your code files and write to the corresponding output files.

Upvotes: 1

Related Questions