note 20584 added to function.substr

From: Date: Tue, 09 Apr 2002 05:09:41 +0000
Subject: note 20584 added to function.substr
Groups: php.notes 
Request: Send a blank email to php-notes+get-28994@lists.php.net to get a copy of this message
When using substr() on the double byte character, for example chinese character, there may be a occasion that trailing character is first byte of the double byte, it may crash you program. E.g substr("¤@¤G¤T¥|", 0, 5) => ¤@¤G? if you do echo (substr("¤@¤G¤T¥|", 0, 5) . "x" ) => "¤@¤G¤x" , your "x" will disapper and became an chinese character. The following function can be used to replace substr to handle these case: function dbyte_substr($str, $start, $len=''){ if($len == ''){ $outstr = substr($str, $start); }else{ $outstr = substr($str, $start, $len); // Check the end bound is an double byte first byte or not if(preg_match("/[\x80-\xFF]$/", $outstr)){ $outstr = substr("$outstr", 0, -1); } } return $outstr; } -- http://www.php.net/manual/en/function.substr.php http://master.php.net/manage/user-notes.php?action=edit+20584 http://master.php.net/manage/user-notes.php?action=delete+20584 http://master.php.net/manage/user-notes.php?action=reject+20584

« previous php.notes (#28994) next »