Skip to content

Instantly share code, notes, and snippets.

@Moln
Last active March 28, 2016 06:59
Show Gist options
  • Select an option

  • Save Moln/7fe1ccd59ac565c4bbb3 to your computer and use it in GitHub Desktop.

Select an option

Save Moln/7fe1ccd59ac565c4bbb3 to your computer and use it in GitHub Desktop.
Markdown table format
<?php
$a = <<<EOT
Markdown table content
EOT;
$a = explode("\n", $a);
$c = "";
$ll = [];
foreach ($a as &$aa) {
$aa = trim($aa, "|\r\n");
$aa = explode("|", $aa);
$aa = array_map("trim", $aa);
$aa = array_values($aa);
foreach ($aa as $k => $dd) {
if (isset($ll[$k])) {
$ll[$k] = strlen($dd) > $ll[$k] ? strlen($dd) : $ll[$k];
} else {
$ll[$k] = strlen($dd);
}
}
}
foreach ($a as $line => $bb) {
if ($line == 1) {
foreach ($bb as $k => &$dd) {
if (str_replace('-', '', $dd)) {
$dd = str_pad($dd, $ll[$k]);
} else { //header
$dd = str_repeat("-", $ll[$k]);
}
}
} else {
foreach ($bb as $k => &$dd) {
$dd = str_pad($dd, $ll[$k]);
}
}
$c .= "| " . implode(" | ", $bb) . " |" . "\n";
}
echo $c;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment