Bloc-note d'un développeur web
Dans : Snippets
16 mai 2010À l’intérieur du code source d’une classe PHP, je souhaite stocker dans un tableau la liste des mots de la version populaire de l’incontournable texte Lorem ipsum. Jusque là rien de bien sorcier. Mais pour des raisons de lisibilité et de conventions de codage je veux obtenir des lignes formées par un maximum de 72 caractères.
Certes je peux m’amuser à le faire à la main, mais pourquoi me fatiguer quand un langage de script tel que PHP me tend la main pour automatiser la procédure ? Et, cerise sur le gâteau, si en plus je peux l’intégrer à mon éditeur préféré, TextMate.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 | #!/usr/bin/env php -n <?php /** * Export a wrapped representation of the words of a text. * * Optional parameters in a line that follows the text: * l<size>. The column width. Default: 72. * s<characters>. Characters to remove. Default: punctuation. * o<asc|desc>. Sort order. Default: none. */ /* # ***** BEGIN LICENSE BLOCK ***** # # Copyright (C) 2010 Mehdi Kabab <http://pioupioum.fr/> # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, # copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following # conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. # # ***** END LICENSE BLOCK ***** */ if (version_compare(PHP_VERSION, '5.0.0', '<')) { throw new Exception('You must have PHP >= 5.0.0!'); } $lenght = 72; // the default column width. $strip = '\p{P}'; // removes the ponctuation $sort = false; // no sorting $raw = file('php://filter/read=string.tolower/resource=php://stdin', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); if (isset($raw[1])) { $args = array_pop($raw); if (preg_match('#^(?:\s{0,}(?:l(?<lenght>\d+)|s(?<strip>.*)|o(?<sort>asc|desc))\s{0,})+$#u', trim($args), $matches)) { if (isset($matches['lenght']) && $matches['lenght']) $lenght = (int) $matches['lenght']; if (isset($matches['strip']) && $matches['strip']) $strip .= '|' . $matches['strip']; if (isset($matches['sort']) && $matches['sort']) $sort = $matches['sort']; } else { array_push($raw, $args); } } $raw = implode(' ', $raw); // Removes punctuation and user characters if ($strip) { $strip = str_replace('#', '\#', $strip); $raw = preg_replace('#(' . $strip . ')#u', '', $raw); } // Estimating indent $start_index = 0; if (isset($_SERVER['TM_INPUT_START_LINE_INDEX'])) { $start_index = $_SERVER['TM_INPUT_START_LINE_INDEX']; } if ('YES' === $_SERVER['TM_SOFT_TABS']) { $tab = str_repeat(' ', $_SERVER['TM_TAB_SIZE']); } else { $tab = "\t"; } $tab_count = floor($start_index / $_SERVER['TM_TAB_SIZE']); $extra_spaces = $start_index % $_SERVER['TM_TAB_SIZE']; $tabs = str_repeat($tab, $tab_count) . str_repeat(' ', $extra_spaces); $tabs_len = $tab_count * $_SERVER['TM_TAB_SIZE'] + $extra_spaces; // Extracting words now! $words = preg_split('#\s+#', $raw); $words = array_map('trim', $words); $words = array_filter(array_unique($words)); // removes empty fields if ($sort) { natsort($words); if ('desc' === $sort) { $words = array_reverse($words); } } $words = sprintf('%s\'%s\'', $tabs, wordwrap(implode("', '", $words), $lenght - $tabs_len, "\n$tabs")); if (0 !== $start_index) { $words = ltrim($words); } if ("''" === $words) { return; } echo $words; |
Sélectionnez le texte à transformer. La transformation du texte se contrôle en ajoutant à la suite une ligne d’arguments optionnels :
l<size>. Ajuster la longueur de ligne. Exemple : l80 pour effectuer une coupure à la colonne 80. Défaut : 72.s<characters>. Exemple : slorem|ipsum pour exclure les mots lorem et ipsum. Défaut : toute ponctuation.o<asc|desc>. Trier la sortie selon les ordres ascendant et descendant. Défaut : aucun tri n’est réalisé.Notez que si votre sélection est précédée par une indentation, alors le script va appliquer cette dernière à chacune des lignes générées en se conformant aux options courantes de TextMate : il générera des espaces si le mode Soft Tabs est activé. Sinon des tabulations complétées d’éventuels espaces.