Last active
March 29, 2026 21:58
-
-
Save szepeviktor/63a250d6e3b83d9aff8d305363291f0b to your computer and use it in GitHub Desktop.
Indent WordPress shortcodes - useful for inspecting page builder post_content
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env php | |
| <?php | |
| $skeletonOnly = in_array('--skeleton', $argv, true); | |
| $input = stream_get_contents(STDIN); | |
| preg_match_all('/\[(\/?)([a-zA-Z_][\w-]*)([^\]]*?)(\/?)\]/', $input, $shortcodeMatches, PREG_OFFSET_CAPTURE); | |
| function extractAttributeNames($attributeText) { | |
| preg_match_all('/([a-zA-Z_][\w:-]*)\s*=\s*(?:"[^"]*"|\'[^\']*\'|[^\s\]]+)|([a-zA-Z_][\w:-]*)/', $attributeText, $attributeMatches); | |
| $attributeNames = array_filter(array_merge($attributeMatches[1], $attributeMatches[2])); | |
| return $attributeNames ? ' ' . implode(' ', $attributeNames) : ''; | |
| } | |
| function formatAttributes($attributeText, $skeletonOnly) { | |
| if ($attributeText === '') { | |
| return ''; | |
| } | |
| if ($skeletonOnly) { | |
| return extractAttributeNames($attributeText); | |
| } | |
| return ' ' . trim($attributeText); | |
| } | |
| $output = ''; | |
| $cursor = 0; | |
| $indentLevel = 0; | |
| foreach ($shortcodeMatches[0] as $matchIndex => $shortcodeMatch) { | |
| $matchOffset = $shortcodeMatch[1]; | |
| $matchedShortcode = $shortcodeMatch[0]; | |
| $isClosingTag = $shortcodeMatches[1][$matchIndex][0] === '/'; | |
| $shortcodeName = $shortcodeMatches[2][$matchIndex][0]; | |
| $attributeText = $shortcodeMatches[3][$matchIndex][0]; | |
| $isSelfClosingTag = $shortcodeMatches[4][$matchIndex][0] === '/'; | |
| $textBetweenShortcodes = substr($input, $cursor, $matchOffset - $cursor); | |
| if (!$skeletonOnly && trim($textBetweenShortcodes) !== '') { | |
| $output .= str_repeat(' ', $indentLevel) . trim($textBetweenShortcodes) . "\n"; | |
| } | |
| if ($isClosingTag) { | |
| $indentLevel--; | |
| } | |
| $output .= str_repeat(' ', $indentLevel) | |
| . '[' | |
| . ($isClosingTag ? '/' : '') | |
| . $shortcodeName | |
| . ($isClosingTag ? '' : formatAttributes($attributeText, $skeletonOnly)) | |
| . ($isSelfClosingTag ? ' /' : '') | |
| . "]\n"; | |
| if (!$isClosingTag && !$isSelfClosingTag) { | |
| $indentLevel++; | |
| } | |
| $cursor = $matchOffset + strlen($matchedShortcode); | |
| } | |
| $remainingText = substr($input, $cursor); | |
| if (!$skeletonOnly && trim($remainingText) !== '') { | |
| $output .= str_repeat(' ', $indentLevel) . trim($remainingText) . "\n"; | |
| } | |
| echo trim($output) . "\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment