Просмотр исходного кода

Feature #272 - A new function api_detect_encoding_html() has been added in the internationalization library. A test for this function has been created.

Ivan Tcholakov 15 лет назад
Родитель
Сommit
7f763d4188

+ 15 - 0
main/inc/lib/internationalization.lib.php

@@ -3173,11 +3173,26 @@ function api_detect_encoding($string) {
 	return $result;
 }
 
+/**
+ * Detects encoding of html-formatted text.
+ * @param string $string				The input html-formatted text.
+ * @return string						Returns the detected encoding.
+ */
+function api_detect_encoding_html($string) {
+	if (@preg_match('/<head.*(<meta[^>]*http-equiv=["\']*content-type[^>]*>).*<\/head>/si', $string, $matches)) {
+		if (@preg_match('/<meta[^>]*charset=(.*)["\';][^>]*>/si', $matches[1], $matches)) {
+			return api_refine_encoding_id(trim($matches[1]));
+		}
+	}
+	return api_detect_encoding(strip_tags($string));
+}
+
 /**
  * Detects encoding of xml-formatted text.
  * @param string $string				The input xml-formatted text.
  * @param string $default_encoding		This is the default encoding to be returned if there is no way the xml-text's encoding to be detected. If it not spesified, the system encoding is assumed then.
  * @return string						Returns the detected encoding.
+ * @todo The second parameter is to be eliminated. See api_detect_encoding_html().
  */
 function api_detect_encoding_xml($string, $default_encoding = null) {
 	if (preg_match(_PCRE_XML_ENCODING, $string, $matches)) {

+ 22 - 0
tests/main/inc/lib/internationalization.lib.test.php

@@ -921,6 +921,28 @@ class TestInternationalization extends UnitTestCase {
 		//var_dump($res);
 	}
 
+	public function test_api_detect_encoding_html() {
+		$meta = '<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-15" />'."\n";
+		$head1 = '<head>'."\n".'<title>Sample Document</title>'."\n".'</head>'."\n";
+		$head2 = '<head>'."\n".'<title>Sample Document</title>'."\n".$meta.'</head>'."\n";
+		$body1 = '<p>This is a sample document for testing encoding detection.</p>'."\n";
+		$body2 = '<body>'."\n".$body1.'</body>';
+		$html1 = $body1; // A html-snippet, see for example some log-files created by the "Chat" tool.
+		$html2 = '<html>'."\n".$head1.$body2."\n".'</html>'; // A full html-document, no encoding has been declared.
+		$html3 = '<html>'."\n".$head2.$body2."\n".'</html>'; // A full html-document, encoding has been declared.
+		$res1 = api_detect_encoding_html($html1);
+		$res2 = api_detect_encoding_html($html2);
+		$res3 = api_detect_encoding_html($html3);
+		$this->assertTrue(
+			$res1 === 'UTF-8'
+			&& $res2 === 'UTF-8'
+			&& $res3 === 'ISO-8859-15'
+		);
+		//var_dump($res1);
+		//var_dump($res2);
+		//var_dump($res3);
+	}
+
 	public function test_api_detect_encoding_xml() {
 		$xml1 = '
 			<Users>