简体   繁体   中英

strange character encoding issues with strings

What would seem to be a simple operations is completely botched by the encoding here. I just want to check if the first character of a string is £. My php file itself is encoded UTF8-Without BOM. Thanks!

<?php
print "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.1//EN' "; 
print "'http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd'>\n";
print "<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='eng' lang='en'>\n";
print "<head>\n";
print "<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />\n";
print "<title>WAMP</title>\n";
print "<meta name='Description' content='Website Under Construction' />\n";
print "</head>\n";
print "<body>\n";
print "<p>\n";

$temp = "£Hello";
$charArray = preg_split('//', $temp, -1);
// preg_match_all('/./', $temp, $charArray);

print_r ($charArray);
print "<br />First Char: $temp[0]";

print "</p>\n";
print "</body>\n";
print "</html>";
?>

Output:

Array ( [0] => [1] => � [2] => � [3] => H [4] => e [5] => l [6] => l [7] => o [8] => )
First Char: �

Desired Output:

Array ( [0] => [1] £ [2] => H [3] => e [4] => l [5] => l [6] => o [7] => ) 
First Char: £

Given that you're sending HTML with appropriate content-type headers, I'm guessing you're running this through the Apache webserver. If not then please ignore me, but there might be a setting elsewhere in the server configuration to do this...

I've run in to this issue before, and absolutally everything must be in UTF8 mode for it to work.

Specifically here, I suspect you need to create a .htaccess file in the same directory as your script containing something like this:

AddDefaultCharset UTF-8

The restart Apache obviously.

Another note here, if you plan to use a MySQL database, you will also need to make sure that the connection is UTF8 encoded, by running the following SQL command after connection:

SET NAMES utf8

Instead of $temp[0] which is not multi-byte aware, try mb_substr() :

if( mb_substr($temp, 0, 1, 'UTF-8') == '£' )
{
  ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM