Skip to content

Instantly share code, notes, and snippets.

@ahomu
Last active December 17, 2015 09:08
Show Gist options
  • Save ahomu/5584991 to your computer and use it in GitHub Desktop.
Save ahomu/5584991 to your computer and use it in GitHub Desktop.
不毛.php
<?php
$content = file_get_contents('./test.txt');
$config = array(
'assocArray' => true,
);
$content = preg_replace_callback('/(\$\{(.*?)\}|\{\{\w+\s(.*?)\}\})/s', function($m) use($config) {
$subject = $m[1];
$needle = !empty($m[2]) ? $m[2] : $m[3];
$chunks = explode(' ', $needle);
foreach ($chunks as $index => $chunk) {
// (演算子|文字リテラル|数値リテラル)でなければ
if (!preg_match('/^([<!=>]+|[\'"]|[0-9])/', $chunk)) {
if ($config['assocArray']) {
$chunk = preg_replace('/\.(\w+)/', "['$1']", $chunk);
} else {
$chunk = str_replace('.', '->', $chunk);
}
// $から始まらなければ
if (strpos($chunk, '$') !== 0) {
// $を足す
$chunk = '$'.$chunk;
}
// lengthプロパティを参照していれば
if ($config['assocArray']) {
if (preg_match("/\['length'\]$/", $chunk)) {
// count関数にする
$chunk = 'count('.preg_replace("/\['length'\]$/", '', $chunk).')';
}
} else {
if (preg_match('/length$/', $chunk)) {
// count関数にする
$chunk = 'count('.preg_replace('/->length$/', '', $chunk).')';
}
}
$chunks[$index] = $chunk;
}
}
$replacement = implode(' ', $chunks);
$result = str_replace($needle, $replacement, $subject);
/*
echo "subject: ".$subject."\n";
echo "needle: ".$needle."\n";
echo "replacement: ".$replacement."\n";
echo "result: ".$result."\n";
*/
return $result;
}, $content);
// {{if condition}}, {{each variable}}, {{else condition}} を変換
$content = preg_replace_callback('/\{\{(\w+)\s(.*?)\}\}/s', function($m) {
$statement = $m[1];
$condition = $m[2];
$result = '';
switch ($statement) {
case 'if':
$result = '<?php if ('.$condition.') { ?>';
break;
case 'else':
$result = '<?php } else if ('.$condition.') { ?>';
break;
case 'each':
$result = '<?php foreach ('.$condition.' as $key => $value ) { ?>';
break;
}
return $result;
}, $content);
// {{else}}, {{/if}}, {{/each}} を変換
$content = preg_replace_callback('/\{\{(\/?\w+)\}\}/', function($m) {
$statement = $m[1];
$result = '';
switch($statement) {
case '/if':
case '/each':
$result = '<?php } ?>';
break;
case 'else':
$result = '<?php } else { ?>';
break;
}
return $result;
}, $content);
// ${$value} を \<?= $value ?\> に変換
$content = preg_replace_callback('/\$\{(.*?)\}/', function($m) {
$variable = $m[1];
$result = '<?= '.$variable.' ?>';
return $result;
}, $content);
file_put_contents('./result.php', $content);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment