Created
August 18, 2020 09:52
-
-
Save MakStashkevich/886c04fd725be3e1edac6dec1466058b to your computer and use it in GitHub Desktop.
Centering multibyte string
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
<?php | |
/** | |
* Multibyte String Centering | |
* | |
* Сhanges the received strings centered relative to each other | |
* | |
* @param string $str1 The first string. | |
* @param string $str2 The second string. | |
* @param string $encoding The encoding to use, defaults to UTF-8. | |
* | |
* @return void Returns nothing, all strings are changed by links. | |
*/ | |
function centering(string &$str1, string &$str2, string $encoding = 'UTF-8') | |
{ | |
$len1 = mb_strlen($str1, $encoding); | |
$len2 = mb_strlen($str2, $encoding); | |
if ($len1 > $len2) { | |
$str2 = str_repeat("\x20", ($len1 - $len2) >> 1) . $str2; | |
} else if ($len1 < $len2) { | |
$str1 = str_repeat("\x20", ($len2 - $len1) >> 1) . $str1; | |
} | |
} | |
///////////////////// TESTS ///////////////////// | |
$str1 = 'Привет мир!'; | |
$str2 = 'тест тест тест тест'; | |
centering($str1, $str2); | |
echo $str1 . PHP_EOL . $str2; | |
// Привет мир! | |
// тест тест тест тест | |
echo PHP_EOL . PHP_EOL; | |
$str1 = '充'; | |
$str2 = '煻充Nhiều byte string đệm煻充煻'; | |
centering($str1, $str2); | |
echo $str1 . PHP_EOL . $str2; | |
// 充 | |
// 煻充Nhiều byte string đệm煻充煻 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment