note 120298 deleted from function.trim by cmb
| From: | cmb@php.net | Date: | Thu, 08 Dec 2016 11:18:19 +0000 |
| Subject: | note 120298 deleted from function.trim by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-208280@lists.php.net to get a copy of this message | ||
Note Submitter: roland at mxchange dot org
----
PHP's "magic byte" for non-ASCII characters may become anoying when you want to find
out if the input string is multi-byte or not (means pure ASCII without any non-ASCII characters).
trim() by default does not remove it from the string, so you may want to do it on your own:
<?php
// Trims string including "space" character and the "magic byte" for non-ASCII
characters
function trimString ($str) {
// Trim away all unwanted characters (including default)
$trimmed = trim($str," \t\n\r\0\x0B\x0A\xc3");
// Return finished string
return $trimmed;
}
?>
Usage: (save file as UTF-8!)
<?php
$str = 'ä';
// For console/prompt:
print 'str=0x' . bin2hex($str) . PHP_EOL;
print 'trim=0x' . bin2hex($trim) . PHP_EOL;
print 'trimString=0x' . bin2hex($trimString) . PHP_EOL;
print 'length after trim()=' . strlen($trim) . PHP_EOL;
print 'length after trimString()=' . strlen($trimString) . PHP_EOL;
?>
Output:
str=0xc3a4
trim=0xc3a4
trimString=0xa4
length after trim()=2
length after trimString()=1
bin2hex() is being used here to show that 0xc3 really exists as first byte. You can test it with any
other multi-byte character.