You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

428 lines
17 KiB

3 years ago
  1. [//]: # (AUTO-GENERATED BY "PHP README Helper": base file -> docs/base.md)
  2. [![Build Status](https://travis-ci.com/voku/portable-ascii.svg?branch=master)](https://travis-ci.com/voku/portable-ascii)
  3. [![Build status](https://ci.appveyor.com/api/projects/status/gnejjnk7qplr7f5t/branch/master?svg=true)](https://ci.appveyor.com/project/voku/portable-ascii/branch/master)
  4. [![Coverage Status](https://coveralls.io/repos/voku/portable-ascii/badge.svg?branch=master&service=github)](https://coveralls.io/github/voku/portable-ascii?branch=master)
  5. [![Codacy Badge](https://api.codacy.com/project/badge/Grade/997c9bb10d1c4791967bdf2e42013e8e)](https://www.codacy.com/app/voku/portable-ascii)
  6. [![Latest Stable Version](https://poser.pugx.org/voku/portable-ascii/v/stable)](https://packagist.org/packages/voku/portable-ascii)
  7. [![Total Downloads](https://poser.pugx.org/voku/portable-ascii/downloads)](https://packagist.org/packages/voku/portable-ascii)
  8. [![License](https://poser.pugx.org/voku/portable-ascii/license)](https://packagist.org/packages/voku/portable-ascii)
  9. [![Donate to this project using Paypal](https://img.shields.io/badge/paypal-donate-yellow.svg)](https://www.paypal.me/moelleken)
  10. [![Donate to this project using Patreon](https://img.shields.io/badge/patreon-donate-yellow.svg)](https://www.patreon.com/voku)
  11. # 🔡 Portable ASCII
  12. ## Description
  13. It is written in PHP (PHP 7+) and can work without "mbstring", "iconv" or any other extra encoding php-extension on your server.
  14. The benefit of Portable ASCII is that it is easy to use, easy to bundle.
  15. The project based on ...
  16. + Sean M. Burke's work (https://metacpan.org/pod/Text::Unidecode)
  17. + Tomaz Solc's work (https://pypi.org/project/Unidecode/)
  18. + Portable UTF-8 work (https://github.com/voku/portable-utf8)
  19. + Daniel St. Jules's work (https://github.com/danielstjules/Stringy)
  20. + Johnny Broadway's work (https://github.com/jbroadway/urlify)
  21. + and many cherry-picks from "github"-gists and "Stack Overflow"-snippets ...
  22. ## Index
  23. * [Alternative](#alternative)
  24. * [Install](#install-portable-ascii-via-composer-require)
  25. * [Why Portable ASCII?](#why-portable-ascii)
  26. * [Requirements and Recommendations](#requirements-and-recommendations)
  27. * [Usage](#usage)
  28. * [Class methods](#class-methods)
  29. * [Unit Test](#unit-test)
  30. * [License and Copyright](#license-and-copyright)
  31. ## Alternative
  32. If you like a more Object Oriented Way to edit strings, then you can take a look at [voku/Stringy](https://github.com/voku/Stringy), it's a fork of "danielstjules/Stringy" but it used the "Portable ASCII"-Class and some extra methods.
  33. ```php
  34. // Portable ASCII
  35. use voku\helper\ASCII;
  36. ASCII::to_transliterate('déjà σσς iıii'); // 'deja sss iiii'
  37. // voku/Stringy
  38. use Stringy\Stringy as S;
  39. $stringy = S::create('déjà σσς iıii');
  40. $stringy->toTransliterate(); // 'deja sss iiii'
  41. ```
  42. ## Install "Portable ASCII" via "composer require"
  43. ```shell
  44. composer require voku/portable-ascii
  45. ```
  46. ## Why Portable ASCII?[]()
  47. I need ASCII char handling in different classes and before I added this functions into "Portable UTF-8",
  48. but this repo is more modular and portable, because it has no dependencies.
  49. ## Requirements and Recommendations
  50. * No extensions are required to run this library. Portable ASCII only needs PCRE library that is available by default since PHP 4.2.0 and cannot be disabled since PHP 5.3.0. "\u" modifier support in PCRE for ASCII handling is not a must.
  51. * PHP 7.0 is the minimum requirement
  52. * PHP 8.0 is also supported
  53. ## Usage
  54. Example: ASCII::to_ascii()
  55. ```php
  56. echo ASCII::to_ascii('�Düsseldorf�', 'de');
  57. // will output
  58. // Duesseldorf
  59. echo ASCII::to_ascii('�Düsseldorf�', 'en');
  60. // will output
  61. // Dusseldorf
  62. ```
  63. # Portable ASCII | API
  64. The API from the "ASCII"-Class is written as small static methods.
  65. ## Class methods
  66. <p id="voku-php-readme-class-methods"></p><table><tr><td><a href="#charsarraybool-replace_extra_symbols-array">charsArray</a>
  67. </td><td><a href="#charsarraywithmultilanguagevaluesbool-replace_extra_symbols-array">charsArrayWithMultiLanguageValues</a>
  68. </td><td><a href="#charsarraywithonelanguagestring-language-bool-replace_extra_symbols-bool-asorigreplacearray-array">charsArrayWithOneLanguage</a>
  69. </td><td><a href="#charsarraywithsinglelanguagevaluesbool-replace_extra_symbols-bool-asorigreplacearray-array">charsArrayWithSingleLanguageValues</a>
  70. </td></tr><tr><td><a href="#cleanstring-str-bool-normalize_whitespace-bool-keep_non_breaking_space-bool-normalize_msword-bool-remove_invisible_characters-string">clean</a>
  71. </td><td><a href="#getalllanguages-string">getAllLanguages</a>
  72. </td><td><a href="#is_asciistring-str-bool">is_ascii</a>
  73. </td><td><a href="#normalize_mswordstring-str-string">normalize_msword</a>
  74. </td></tr><tr><td><a href="#normalize_whitespacestring-str-bool-keepnonbreakingspace-bool-keepbidiunicodecontrols-bool-replaceseparatorswithnewline-string">normalize_whitespace</a>
  75. </td><td><a href="#remove_invisible_charactersstring-str-bool-url_encoded-string-replacement-bool-keep_control_characters-string">remove_invisible_characters</a>
  76. </td><td><a href="#to_asciistring-str-string-language-bool-remove_unsupported_chars-bool-replace_extra_symbols-bool-use_transliterate-boolnull-replace_single_chars_only-string">to_ascii</a>
  77. </td><td><a href="#to_filenamestring-str-bool-use_transliterate-string-fallback_char-string">to_filename</a>
  78. </td></tr><tr><td><a href="#to_slugifystring-str-string-separator-string-language-string-replacements-bool-replace_extra_symbols-bool-use_str_to_lower-bool-use_transliterate-string">to_slugify</a>
  79. </td><td><a href="#to_transliteratestring-str-stringnull-unknown-bool-strict-string">to_transliterate</a>
  80. </td></tr></table>
  81. #### charsArray(bool $replace_extra_symbols): array
  82. <a href="#voku-php-readme-class-methods"></a>
  83. Returns an replacement array for ASCII methods.
  84. EXAMPLE: <code>
  85. $array = ASCII::charsArray();
  86. var_dump($array['ru']['б']); // 'b'
  87. </code>
  88. **Parameters:**
  89. - `bool $replace_extra_symbols [optional] <p>Add some more replacements e.g. "£" with " pound ".</p>`
  90. **Return:**
  91. - `array`
  92. --------
  93. #### charsArrayWithMultiLanguageValues(bool $replace_extra_symbols): array
  94. <a href="#voku-php-readme-class-methods"></a>
  95. Returns an replacement array for ASCII methods with a mix of multiple languages.
  96. EXAMPLE: <code>
  97. $array = ASCII::charsArrayWithMultiLanguageValues();
  98. var_dump($array['b']); // ['β', 'б', 'ဗ', 'ბ', 'ب']
  99. </code>
  100. **Parameters:**
  101. - `bool $replace_extra_symbols [optional] <p>Add some more replacements e.g. "£" with " pound ".</p>`
  102. **Return:**
  103. - `array <p>An array of replacements.</p>`
  104. --------
  105. #### charsArrayWithOneLanguage(string $language, bool $replace_extra_symbols, bool $asOrigReplaceArray): array
  106. <a href="#voku-php-readme-class-methods"></a>
  107. Returns an replacement array for ASCII methods with one language.
  108. For example, German will map 'ä' to 'ae', while other languages
  109. will simply return e.g. 'a'.
  110. EXAMPLE: <code>
  111. $array = ASCII::charsArrayWithOneLanguage('ru');
  112. $tmpKey = \array_search('yo', $array['replace']);
  113. echo $array['orig'][$tmpKey]; // 'ё'
  114. </code>
  115. **Parameters:**
  116. - `string $language [optional] <p>Language of the source string e.g.: en, de_at, or de-ch.
  117. (default is 'en') | ASCII::*_LANGUAGE_CODE</p>`
  118. - `bool $replace_extra_symbols [optional] <p>Add some more replacements e.g. "£" with " pound ".</p>`
  119. - `bool $asOrigReplaceArray [optional] <p>TRUE === return {orig: string[], replace: string[]}
  120. array</p>`
  121. **Return:**
  122. - `array <p>An array of replacements.</p>`
  123. --------
  124. #### charsArrayWithSingleLanguageValues(bool $replace_extra_symbols, bool $asOrigReplaceArray): array
  125. <a href="#voku-php-readme-class-methods"></a>
  126. Returns an replacement array for ASCII methods with multiple languages.
  127. EXAMPLE: <code>
  128. $array = ASCII::charsArrayWithSingleLanguageValues();
  129. $tmpKey = \array_search('hnaik', $array['replace']);
  130. echo $array['orig'][$tmpKey]; // '၌'
  131. </code>
  132. **Parameters:**
  133. - `bool $replace_extra_symbols [optional] <p>Add some more replacements e.g. "£" with " pound ".</p>`
  134. - `bool $asOrigReplaceArray [optional] <p>TRUE === return {orig: string[], replace: string[]}
  135. array</p>`
  136. **Return:**
  137. - `array <p>An array of replacements.</p>`
  138. --------
  139. #### clean(string $str, bool $normalize_whitespace, bool $keep_non_breaking_space, bool $normalize_msword, bool $remove_invisible_characters): string
  140. <a href="#voku-php-readme-class-methods"></a>
  141. Accepts a string and removes all non-UTF-8 characters from it + extras if needed.
  142. **Parameters:**
  143. - `string $str <p>The string to be sanitized.</p>`
  144. - `bool $normalize_whitespace [optional] <p>Set to true, if you need to normalize the
  145. whitespace.</p>`
  146. - `bool $keep_non_breaking_space [optional] <p>Set to true, to keep non-breaking-spaces, in
  147. combination with
  148. $normalize_whitespace</p>`
  149. - `bool $normalize_msword [optional] <p>Set to true, if you need to normalize MS Word chars
  150. e.g.: "…"
  151. => "..."</p>`
  152. - `bool $remove_invisible_characters [optional] <p>Set to false, if you not want to remove invisible
  153. characters e.g.: "\0"</p>`
  154. **Return:**
  155. - `string <p>A clean UTF-8 string.</p>`
  156. --------
  157. #### getAllLanguages(): string[]
  158. <a href="#voku-php-readme-class-methods"></a>
  159. Get all languages from the constants "ASCII::.*LANGUAGE_CODE".
  160. **Parameters:**
  161. __nothing__
  162. **Return:**
  163. - `string[]`
  164. --------
  165. #### is_ascii(string $str): bool
  166. <a href="#voku-php-readme-class-methods"></a>
  167. Checks if a string is 7 bit ASCII.
  168. EXAMPLE: <code>
  169. ASCII::is_ascii('白'); // false
  170. </code>
  171. **Parameters:**
  172. - `string $str <p>The string to check.</p>`
  173. **Return:**
  174. - `bool <p>
  175. <strong>true</strong> if it is ASCII<br>
  176. <strong>false</strong> otherwise
  177. </p>`
  178. --------
  179. #### normalize_msword(string $str): string
  180. <a href="#voku-php-readme-class-methods"></a>
  181. Returns a string with smart quotes, ellipsis characters, and dashes from
  182. Windows-1252 (commonly used in Word documents) replaced by their ASCII
  183. equivalents.
  184. EXAMPLE: <code>
  185. ASCII::normalize_msword('„Abcdef…”'); // '"Abcdef..."'
  186. </code>
  187. **Parameters:**
  188. - `string $str <p>The string to be normalized.</p>`
  189. **Return:**
  190. - `string <p>A string with normalized characters for commonly used chars in Word documents.</p>`
  191. --------
  192. #### normalize_whitespace(string $str, bool $keepNonBreakingSpace, bool $keepBidiUnicodeControls, bool $replaceSeparatorsWithNewline): string
  193. <a href="#voku-php-readme-class-methods"></a>
  194. Normalize the whitespace.
  195. EXAMPLE: <code>
  196. ASCII::normalize_whitespace("abc-\xc2\xa0-öäü-\xe2\x80\xaf-\xE2\x80\xAC", true); // "abc-\xc2\xa0-öäü- -"
  197. </code>
  198. **Parameters:**
  199. - `string $str <p>The string to be normalized.</p>`
  200. - `bool $keepNonBreakingSpace [optional] <p>Set to true, to keep non-breaking-spaces.</p>`
  201. - `bool $keepBidiUnicodeControls [optional] <p>Set to true, to keep non-printable (for the web)
  202. bidirectional text chars.</p>`
  203. - `bool $replaceSeparatorsWithNewline [optional] <p>Set to true, to convert LINE and PARAGRAPH SEPARATOR with "\n".</p>`
  204. **Return:**
  205. - `string <p>A string with normalized whitespace.</p>`
  206. --------
  207. #### remove_invisible_characters(string $str, bool $url_encoded, string $replacement, bool $keep_control_characters): string
  208. <a href="#voku-php-readme-class-methods"></a>
  209. Remove invisible characters from a string.
  210. e.g.: This prevents sandwiching null characters between ascii characters, like Java\0script.
  211. copy&past from https://github.com/bcit-ci/CodeIgniter/blob/develop/system/core/Common.php
  212. **Parameters:**
  213. - `string $str`
  214. - `bool $url_encoded`
  215. - `string $replacement`
  216. - `bool $keep_control_characters`
  217. **Return:**
  218. - `string`
  219. --------
  220. #### to_ascii(string $str, string $language, bool $remove_unsupported_chars, bool $replace_extra_symbols, bool $use_transliterate, bool|null $replace_single_chars_only): string
  221. <a href="#voku-php-readme-class-methods"></a>
  222. Returns an ASCII version of the string. A set of non-ASCII characters are
  223. replaced with their closest ASCII counterparts, and the rest are removed
  224. by default. The language or locale of the source string can be supplied
  225. for language-specific transliteration in any of the following formats:
  226. en, en_GB, or en-GB. For example, passing "de" results in "äöü" mapping
  227. to "aeoeue" rather than "aou" as in other languages.
  228. EXAMPLE: <code>
  229. ASCII::to_ascii('�Düsseldorf�', 'en'); // Dusseldorf
  230. </code>
  231. **Parameters:**
  232. - `string $str <p>The input string.</p>`
  233. - `string $language [optional] <p>Language of the source string.
  234. (default is 'en') | ASCII::*_LANGUAGE_CODE</p>`
  235. - `bool $remove_unsupported_chars [optional] <p>Whether or not to remove the
  236. unsupported characters.</p>`
  237. - `bool $replace_extra_symbols [optional] <p>Add some more replacements e.g. "£" with " pound
  238. ".</p>`
  239. - `bool $use_transliterate [optional] <p>Use ASCII::to_transliterate() for unknown chars.</p>`
  240. - `bool|null $replace_single_chars_only [optional] <p>Single char replacement is better for the
  241. performance, but some languages need to replace more then one char
  242. at the same time. | NULL === auto-setting, depended on the
  243. language</p>`
  244. **Return:**
  245. - `string <p>A string that contains only ASCII characters.</p>`
  246. --------
  247. #### to_filename(string $str, bool $use_transliterate, string $fallback_char): string
  248. <a href="#voku-php-readme-class-methods"></a>
  249. Convert given string to safe filename (and keep string case).
  250. EXAMPLE: <code>
  251. ASCII::to_filename('שדגשדג.png', true)); // 'shdgshdg.png'
  252. </code>
  253. **Parameters:**
  254. - `string $str`
  255. - `bool $use_transliterate <p>ASCII::to_transliterate() is used by default - unsafe characters are
  256. simply replaced with hyphen otherwise.</p>`
  257. - `string $fallback_char`
  258. **Return:**
  259. - `string <p>A string that contains only safe characters for a filename.</p>`
  260. --------
  261. #### to_slugify(string $str, string $separator, string $language, string[] $replacements, bool $replace_extra_symbols, bool $use_str_to_lower, bool $use_transliterate): string
  262. <a href="#voku-php-readme-class-methods"></a>
  263. Converts the string into an URL slug. This includes replacing non-ASCII
  264. characters with their closest ASCII equivalents, removing remaining
  265. non-ASCII and non-alphanumeric characters, and replacing whitespace with
  266. $separator. The separator defaults to a single dash, and the string
  267. is also converted to lowercase. The language of the source string can
  268. also be supplied for language-specific transliteration.
  269. **Parameters:**
  270. - `string $str`
  271. - `string $separator [optional] <p>The string used to replace whitespace.</p>`
  272. - `string $language [optional] <p>Language of the source string.
  273. (default is 'en') | ASCII::*_LANGUAGE_CODE</p>`
  274. - `array<string, string> $replacements [optional] <p>A map of replaceable strings.</p>`
  275. - `bool $replace_extra_symbols [optional] <p>Add some more replacements e.g. "£" with "
  276. pound ".</p>`
  277. - `bool $use_str_to_lower [optional] <p>Use "string to lower" for the input.</p>`
  278. - `bool $use_transliterate [optional] <p>Use ASCII::to_transliterate() for unknown
  279. chars.</p>`
  280. **Return:**
  281. - `string <p>A string that has been converted to an URL slug.</p>`
  282. --------
  283. #### to_transliterate(string $str, string|null $unknown, bool $strict): string
  284. <a href="#voku-php-readme-class-methods"></a>
  285. Returns an ASCII version of the string. A set of non-ASCII characters are
  286. replaced with their closest ASCII counterparts, and the rest are removed
  287. unless instructed otherwise.
  288. EXAMPLE: <code>
  289. ASCII::to_transliterate('déjà σσς iıii'); // 'deja sss iiii'
  290. </code>
  291. **Parameters:**
  292. - `string $str <p>The input string.</p>`
  293. - `string|null $unknown [optional] <p>Character use if character unknown. (default is '?')
  294. But you can also use NULL to keep the unknown chars.</p>`
  295. - `bool $strict [optional] <p>Use "transliterator_transliterate()" from PHP-Intl`
  296. **Return:**
  297. - `string <p>A String that contains only ASCII characters.</p>`
  298. --------
  299. ## Unit Test
  300. 1) [Composer](https://getcomposer.org) is a prerequisite for running the tests.
  301. ```
  302. composer install
  303. ```
  304. 2) The tests can be executed by running this command from the root directory:
  305. ```bash
  306. ./vendor/bin/phpunit
  307. ```
  308. ### Support
  309. For support and donations please visit [Github](https://github.com/voku/portable-ascii/) | [Issues](https://github.com/voku/portable-ascii/issues) | [PayPal](https://paypal.me/moelleken) | [Patreon](https://www.patreon.com/voku).
  310. For status updates and release announcements please visit [Releases](https://github.com/voku/portable-ascii/releases) | [Twitter](https://twitter.com/suckup_de) | [Patreon](https://www.patreon.com/voku/posts).
  311. For professional support please contact [me](https://about.me/voku).
  312. ### Thanks
  313. - Thanks to [GitHub](https://github.com) (Microsoft) for hosting the code and a good infrastructure including Issues-Managment, etc.
  314. - Thanks to [IntelliJ](https://www.jetbrains.com) as they make the best IDEs for PHP and they gave me an open source license for PhpStorm!
  315. - Thanks to [Travis CI](https://travis-ci.com/) for being the most awesome, easiest continous integration tool out there!
  316. - Thanks to [StyleCI](https://styleci.io/) for the simple but powerful code style check.
  317. - Thanks to [PHPStan](https://github.com/phpstan/phpstan) && [Psalm](https://github.com/vimeo/psalm) for really great Static analysis tools and for discover bugs in the code!
  318. ### License and Copyright
  319. Released under the MIT License - see `LICENSE.txt` for details.