summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/SemanticMediaWiki/src/Utils/CharExaminer.php
blob: e7d07c4886760c5813ee0e32347f5c51a58cb59e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php

namespace SMW\Utils;

/**
 * @license GNU GPL v2+
 * @since 3.0
 *
 * @author mwjames
 */
class CharExaminer {

	const CYRILLIC = 'CYRILLIC';
	const LATIN = 'LATIN';
	const HIRAGANA_KATAKANA = 'HIRAGANA_KATAKANA';
	const HANGUL = 'HANGUL';
	const CJK_UNIFIED = 'CJK_UNIFIED';
	const HAN = 'HAN';

	/**
	 * @since 3.0
	 *
	 * @param string $text
	 *
	 * @return boolean
	 */
	public static function isCJK( $text ) {

		if ( self::contains( self::HAN, $text ) ) {
			return true;
		}

		if ( self::contains( self::HIRAGANA_KATAKANA, $text ) ) {
			return true;
		}

		if ( self::contains( self::HANGUL, $text ) ) {
			return true;
		}

		if ( self::contains( self::CJK_UNIFIED, $text ) ) {
			return true;
		}

		return false;
	}

	/**
	 * @see http://jrgraphix.net/research/unicode_blocks.php
	 * @since 0.1
	 *
	 * @param string $type
	 * @param string $text
	 *
	 * @return boolean
	 */
	public static function contains( $type, $text ) {

		if ( $type === self::CYRILLIC ) {
			return preg_match('/\p{Cyrillic}/u', $text ) > 0;
		}

		if ( $type === self::LATIN ) {
			return preg_match('/\p{Latin}/u', $text ) > 0;
		}

		if ( $type === self::HAN ) {
			return preg_match('/\p{Han}/u', $text ) > 0;
		}

		if ( $type === self::HIRAGANA_KATAKANA ) {
			return preg_match('/[\x{3040}-\x{309F}]/u', $text ) > 0 || preg_match('/[\x{30A0}-\x{30FF}]/u', $text ) > 0; // isHiragana || isKatakana
		}

		if ( $type === self::HANGUL ) {
			return preg_match('/[\x{3130}-\x{318F}]/u', $text ) > 0 || preg_match('/[\x{AC00}-\x{D7AF}]/u', $text ) > 0;
		}

		// @see https://en.wikipedia.org/wiki/CJK_Unified_Ideographs
		// Chinese, Japanese and Korean (CJK) scripts share common characters
		// known as CJK characters

		if ( $type === self::CJK_UNIFIED ) {
			return preg_match('/[\x{4e00}-\x{9fa5}]/u', $text ) > 0;
		}

		return false;
	}

}