Skip to content

Instantly share code, notes, and snippets.

@baizhebz
Last active May 9, 2016 09:10
Show Gist options
  • Save baizhebz/f36a9bf9e8b2f98e9501fb8d01fcfb45 to your computer and use it in GitHub Desktop.
Save baizhebz/f36a9bf9e8b2f98e9501fb8d01fcfb45 to your computer and use it in GitHub Desktop.
A simple&basic tools for html convert to jsx in React.
<?php
if ($argc === 1) {
print("please input file name.\n");
exit(-1);
}
$file_name = $argv[1];
if (!file_exists($file_name)) {
print("file does not exists.\n");
exit(-1);
}
$handler = @fopen($file_name, 'r');
if (!$handler) {
print("could not read file content.\n");
exit(-1);
}
$new_content = '';
while (($line = fgets($handler, 4096)) !== false) {
$pattern = '#style=(\".+?\")#';
$match_cnt = preg_match_all($pattern, $line, $matches);
if ($match_cnt > 0) {
// print(trim($line) . "\n");
$caputres = $matches[1];
// print_r($caputres);
$replacements = [];
foreach ($caputres as $style) {
$_replace = 'style={{';
$style = trim($style, "\"");
$segs = explode(';', $style);
$_reps = [];
foreach ($segs as $_rule) {
if (!trim($_rule)) continue;
$_rep = '';
$_rule = trim($_rule);
$_segs = explode(':', $_rule, 2);
$_f = $_segs[0];
$_b = trim($_segs[1]);
if (stripos($_f, "-") !== false) {
$_rep = join('', explode('-', $_f, 2)) . ':';
} else {
$_rep = "{$_f}:";
}
$_rep .= "\"{$_b}\"";
$_reps[] = $_rep;
}
$_replace .= join(", ", $_reps) . '}}';
$replacements[] = $_replace;
}
// print_r($replacements);
$new_line = preg_replace(array_pad([$pattern], $match_cnt, $pattern), $replacements, $line, 1);
// print(trim($new_line) . "\n");
$new_content .= $new_line;
} else {
$new_content .= $line;
}
}
if (!feof($handler)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handler);
$patterns = ['#class=#', '#cellspacing=#', '#cellpadding=#', '#bgcolor=#', '#colspan=#', '#rowspan=#'];
$replaces = ['className=', 'cellSpacing=', 'cellPadding=', 'bgColor=', 'colSpan=', 'rowSpan='];
foreach ($patterns as $index=>$each) {
$new_content = preg_replace($each, $replaces[$index], $new_content);
}
$name = basename($file_name);
file_put_contents('format-'.$name, $new_content);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment