Last active
March 28, 2023 13:04
-
-
Save niquenen/d06a55ddf11f4a08a421750c2ccb96b6 to your computer and use it in GitHub Desktop.
PHP function to replace all characters with an ASCII equivalent.
This file contains 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
<?php | |
/** | |
* @author niquenen | |
* @company H2V Solutions | |
* @created_at 2020-02-18 10:54:10 | |
* @updated_by niquenen | |
* @updated_at 2022-11-04 15:16:13 | |
*/ | |
/** | |
* Replace all characters with an ASCII equivalent. | |
* This function requires `mbstring` and `iconv` libraries. | |
* | |
* @see https://stackoverflow.com/questions/1176904 How to remove all | |
* non printable characters | |
* in a string? | |
* | |
* @param string $str Original string converted. | |
* @param bool $printable Checks for any printable characters. | |
* @return string|null ASCII encoded string or null if the functions are not | |
* found or if a problem has occurred. | |
*/ | |
function toAscii(string $str, bool $printable = false): ?string | |
{ | |
$encoding = ''; | |
if (!function_exists('mb_detect_encoding') || !function_exists('iconv')) { | |
return null; | |
} | |
else if ($printable) { | |
$str = preg_replace('/[\x00-\x1F\x7F]/u', '', $str); | |
} | |
$encoding = mb_detect_encoding($str, mb_detect_order(), true); | |
if ($encoding === false) { | |
return null; | |
} | |
else if ($encoding != 'ASCII') { | |
$str = iconv($encoding, 'ASCII//TRANSLIT', $str); | |
return $str === false ? null : preg_replace('#[^-\w]+#', '', $str); | |
} | |
return $str; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For more information about the question:
I redirect to this post on Stack Overflow.
An example of the function can be found below (or on PHPSandbox):