Passed
Pull Request — master (#21)
by
unknown
01:57 queued 18s
created
src/Multibyte.php 2 patches
Indentation   +173 added lines, -173 removed lines patch added patch discarded remove patch
@@ -7,177 +7,177 @@
 block discarded – undo
7 7
  */
8 8
 class Multibyte
9 9
 {
10
-    //https://stackoverflow.com/questions/20025030/convert-all-types-of-smart-quotes-with-php
11
-    private static $unicodeCharacterMap = [
12
-        // Windows codepage 1252
13
-        "\xC2\x82" => "'", // U+0082⇒U+201A single low-9 quotation mark
14
-        "\xC2\x84" => '"', // U+0084⇒U+201E double low-9 quotation mark
15
-        "\xC2\x8B" => "'", // U+008B⇒U+2039 single left-pointing angle quotation mark
16
-        "\xC2\x91" => "'", // U+0091⇒U+2018 left single quotation mark
17
-        "\xC2\x92" => "'", // U+0092⇒U+2019 right single quotation mark
18
-        "\xC2\x93" => '"', // U+0093⇒U+201C left double quotation mark
19
-        "\xC2\x94" => '"', // U+0094⇒U+201D right double quotation mark
20
-        "\xC2\x9B" => "'", // U+009B⇒U+203A single right-pointing angle quotation mark
21
-        // Regular Unicode     // U+0022 quotation mark (")
22
-        // U+0027 apostrophe     (')
23
-        "\xC2\xAB" => '"', // U+00AB left-pointing double angle quotation mark
24
-        "\xC2\xBB" => '"', // U+00BB right-pointing double angle quotation mark
25
-        "\xE2\x80\x98" => "'", // U+2018 left single quotation mark
26
-        "\xE2\x80\x99" => "'", // U+2019 right single quotation mark
27
-        "\xE2\x80\x9A" => "'", // U+201A single low-9 quotation mark
28
-        "\xE2\x80\x9B" => "'", // U+201B single high-reversed-9 quotation mark
29
-        "\xE2\x80\x9C" => '"', // U+201C left double quotation mark
30
-        "\xE2\x80\x9D" => '"', // U+201D right double quotation mark
31
-        "\xE2\x80\x9E" => '"', // U+201E double low-9 quotation mark
32
-        "\xE2\x80\x9F" => '"', // U+201F double high-reversed-9 quotation mark
33
-        "\xE2\x80\xB9" => "'", // U+2039 single left-pointing angle quotation mark
34
-        "\xE2\x80\xBA" => "'", // U+203A single right-pointing angle quotation mark
35
-    ];
36
-
37
-    /**
38
-     * Replace
39
-     *
40
-     * @staticvar array $chr_map
41
-     * @param string $string
42
-     * @return string
43
-     */
44
-    public static function cleanUnicode($string)
45
-    {
46
-        $character = array_keys(self::$unicodeCharacterMap); // but: for efficiency you should
47
-        $replace = array_values(self::$unicodeCharacterMap); // pre-calculate these two arrays
48
-        return str_replace($character, $replace, html_entity_decode($string, ENT_QUOTES, "UTF-8"));
49
-    }
50
-
51
-    /**
52
-     * Multibyte.php safe version of standard trim() function.
53
-     *
54
-     * @param string $string
55
-     * @return string
56
-     */
57
-    public static function trim($string)
58
-    {
59
-        return mb_ereg_replace('^\s*([\s\S]*?)\s*$', '\1', $string);
60
-    }
61
-
62
-    /**
63
-     * A cross between mb_split and preg_split, adding the preg_split flags
64
-     * to mb_split.
65
-     *
66
-     * @param string $pattern
67
-     * @param string $string
68
-     * @param int $limit
69
-     * @param int $flags
70
-     * @return array
71
-     */
72
-    public static function split($pattern, $string, $limit = -1, $flags = 0)
73
-    {
74
-        $offset_capture = (bool)($flags & PREG_SPLIT_OFFSET_CAPTURE);
75
-
76
-        $lengths = self::getSplitLengths($pattern, $string);
77
-
78
-        // Substrings
79
-        $parts = [];
80
-        $position = 0;
81
-        $count = 1;
82
-        foreach ($lengths as $length) {
83
-            if (self::isLastPart($length, $flags, $limit, $count)) {
84
-                $parts[] = self::makePart($string, $position, null, $offset_capture);
85
-                return $parts;
86
-            }
87
-
88
-            if (self::isPart($length, $flags)) {
89
-                $parts[] = self::makePart($string, $position, $length[0], $offset_capture);
90
-            }
91
-
92
-            $position += $length[0];
93
-        }
94
-
95
-        return $parts;
96
-    }
97
-
98
-    /**
99
-     * @param $length
100
-     * @param $flags
101
-     * @param $limit
102
-     * @param $count
103
-     * @return bool
104
-     */
105
-    private static function isLastPart($length, $flags, $limit, &$count)
106
-    {
107
-        $split_empty = !($flags & PREG_SPLIT_NO_EMPTY) || $length[0];
108
-        $is_delimiter = $length[1];
109
-
110
-        return $limit > 0
111
-            && !$is_delimiter
112
-            && $split_empty
113
-            && ++$count > $limit;
114
-    }
115
-
116
-    /**
117
-     * @param $length
118
-     * @param $flags
119
-     * @return bool
120
-     */
121
-    private static function isPart($length, $flags)
122
-    {
123
-        $split_empty = !($flags & PREG_SPLIT_NO_EMPTY) || $length[0];
124
-        $is_delimiter = $length[1];
125
-        $is_captured = ($flags & PREG_SPLIT_DELIM_CAPTURE) && $length[2];
126
-
127
-        return (!$is_delimiter
128
-                || $is_captured)
129
-            && $split_empty;
130
-    }
131
-
132
-    /**
133
-     * Make part
134
-     * @param string $string
135
-     * @param integer $position
136
-     * @param integer|null $length
137
-     * @param bool $offset_capture
138
-     * @return array|string
139
-     */
140
-    private static function makePart($string, $position, $length = null, $offset_capture = false)
141
-    {
142
-        $cut = mb_strcut($string, $position, $length);
143
-
144
-        return $offset_capture
145
-            ? [$cut, $position]
146
-            : $cut;
147
-    }
148
-
149
-    /**
150
-     * Splits the string by pattern and for each element (part or split) returns:
151
-     *  [ 0 => length, 1 => is_delimiter?, 2 =>
152
-     *
153
-     * @param $pattern
154
-     * @param $string
155
-     * @return array
156
-     */
157
-    private static function getSplitLengths($pattern, $string)
158
-    {
159
-        $strlen = strlen($string); // bytes!
160
-        $lengths = [];
161
-
162
-        mb_ereg_search_init($string);
163
-
164
-        $position = 0;
165
-        while ($position < $strlen
166
-            && ($array = mb_ereg_search_pos($pattern, '')) !== false) {
167
-            // capture split
168
-            $lengths[] = [$array[0] - $position, false, null];
169
-
170
-            // move position
171
-            $position = $array[0] + $array[1];
172
-
173
-            // capture delimiter
174
-            $regs = mb_ereg_search_getregs();
175
-            $lengths[] = [$array[1], true, isset($regs[1]) && $regs[1]];
176
-        }
177
-
178
-        // Add last bit, if not ending with split
179
-        $lengths[] = [$strlen - $position, false, null];
180
-
181
-        return $lengths;
182
-    }
10
+	//https://stackoverflow.com/questions/20025030/convert-all-types-of-smart-quotes-with-php
11
+	private static $unicodeCharacterMap = [
12
+		// Windows codepage 1252
13
+		"\xC2\x82" => "'", // U+0082⇒U+201A single low-9 quotation mark
14
+		"\xC2\x84" => '"', // U+0084⇒U+201E double low-9 quotation mark
15
+		"\xC2\x8B" => "'", // U+008B⇒U+2039 single left-pointing angle quotation mark
16
+		"\xC2\x91" => "'", // U+0091⇒U+2018 left single quotation mark
17
+		"\xC2\x92" => "'", // U+0092⇒U+2019 right single quotation mark
18
+		"\xC2\x93" => '"', // U+0093⇒U+201C left double quotation mark
19
+		"\xC2\x94" => '"', // U+0094⇒U+201D right double quotation mark
20
+		"\xC2\x9B" => "'", // U+009B⇒U+203A single right-pointing angle quotation mark
21
+		// Regular Unicode     // U+0022 quotation mark (")
22
+		// U+0027 apostrophe     (')
23
+		"\xC2\xAB" => '"', // U+00AB left-pointing double angle quotation mark
24
+		"\xC2\xBB" => '"', // U+00BB right-pointing double angle quotation mark
25
+		"\xE2\x80\x98" => "'", // U+2018 left single quotation mark
26
+		"\xE2\x80\x99" => "'", // U+2019 right single quotation mark
27
+		"\xE2\x80\x9A" => "'", // U+201A single low-9 quotation mark
28
+		"\xE2\x80\x9B" => "'", // U+201B single high-reversed-9 quotation mark
29
+		"\xE2\x80\x9C" => '"', // U+201C left double quotation mark
30
+		"\xE2\x80\x9D" => '"', // U+201D right double quotation mark
31
+		"\xE2\x80\x9E" => '"', // U+201E double low-9 quotation mark
32
+		"\xE2\x80\x9F" => '"', // U+201F double high-reversed-9 quotation mark
33
+		"\xE2\x80\xB9" => "'", // U+2039 single left-pointing angle quotation mark
34
+		"\xE2\x80\xBA" => "'", // U+203A single right-pointing angle quotation mark
35
+	];
36
+
37
+	/**
38
+	 * Replace
39
+	 *
40
+	 * @staticvar array $chr_map
41
+	 * @param string $string
42
+	 * @return string
43
+	 */
44
+	public static function cleanUnicode($string)
45
+	{
46
+		$character = array_keys(self::$unicodeCharacterMap); // but: for efficiency you should
47
+		$replace = array_values(self::$unicodeCharacterMap); // pre-calculate these two arrays
48
+		return str_replace($character, $replace, html_entity_decode($string, ENT_QUOTES, "UTF-8"));
49
+	}
50
+
51
+	/**
52
+	 * Multibyte.php safe version of standard trim() function.
53
+	 *
54
+	 * @param string $string
55
+	 * @return string
56
+	 */
57
+	public static function trim($string)
58
+	{
59
+		return mb_ereg_replace('^\s*([\s\S]*?)\s*$', '\1', $string);
60
+	}
61
+
62
+	/**
63
+	 * A cross between mb_split and preg_split, adding the preg_split flags
64
+	 * to mb_split.
65
+	 *
66
+	 * @param string $pattern
67
+	 * @param string $string
68
+	 * @param int $limit
69
+	 * @param int $flags
70
+	 * @return array
71
+	 */
72
+	public static function split($pattern, $string, $limit = -1, $flags = 0)
73
+	{
74
+		$offset_capture = (bool)($flags & PREG_SPLIT_OFFSET_CAPTURE);
75
+
76
+		$lengths = self::getSplitLengths($pattern, $string);
77
+
78
+		// Substrings
79
+		$parts = [];
80
+		$position = 0;
81
+		$count = 1;
82
+		foreach ($lengths as $length) {
83
+			if (self::isLastPart($length, $flags, $limit, $count)) {
84
+				$parts[] = self::makePart($string, $position, null, $offset_capture);
85
+				return $parts;
86
+			}
87
+
88
+			if (self::isPart($length, $flags)) {
89
+				$parts[] = self::makePart($string, $position, $length[0], $offset_capture);
90
+			}
91
+
92
+			$position += $length[0];
93
+		}
94
+
95
+		return $parts;
96
+	}
97
+
98
+	/**
99
+	 * @param $length
100
+	 * @param $flags
101
+	 * @param $limit
102
+	 * @param $count
103
+	 * @return bool
104
+	 */
105
+	private static function isLastPart($length, $flags, $limit, &$count)
106
+	{
107
+		$split_empty = !($flags & PREG_SPLIT_NO_EMPTY) || $length[0];
108
+		$is_delimiter = $length[1];
109
+
110
+		return $limit > 0
111
+			&& !$is_delimiter
112
+			&& $split_empty
113
+			&& ++$count > $limit;
114
+	}
115
+
116
+	/**
117
+	 * @param $length
118
+	 * @param $flags
119
+	 * @return bool
120
+	 */
121
+	private static function isPart($length, $flags)
122
+	{
123
+		$split_empty = !($flags & PREG_SPLIT_NO_EMPTY) || $length[0];
124
+		$is_delimiter = $length[1];
125
+		$is_captured = ($flags & PREG_SPLIT_DELIM_CAPTURE) && $length[2];
126
+
127
+		return (!$is_delimiter
128
+				|| $is_captured)
129
+			&& $split_empty;
130
+	}
131
+
132
+	/**
133
+	 * Make part
134
+	 * @param string $string
135
+	 * @param integer $position
136
+	 * @param integer|null $length
137
+	 * @param bool $offset_capture
138
+	 * @return array|string
139
+	 */
140
+	private static function makePart($string, $position, $length = null, $offset_capture = false)
141
+	{
142
+		$cut = mb_strcut($string, $position, $length);
143
+
144
+		return $offset_capture
145
+			? [$cut, $position]
146
+			: $cut;
147
+	}
148
+
149
+	/**
150
+	 * Splits the string by pattern and for each element (part or split) returns:
151
+	 *  [ 0 => length, 1 => is_delimiter?, 2 =>
152
+	 *
153
+	 * @param $pattern
154
+	 * @param $string
155
+	 * @return array
156
+	 */
157
+	private static function getSplitLengths($pattern, $string)
158
+	{
159
+		$strlen = strlen($string); // bytes!
160
+		$lengths = [];
161
+
162
+		mb_ereg_search_init($string);
163
+
164
+		$position = 0;
165
+		while ($position < $strlen
166
+			&& ($array = mb_ereg_search_pos($pattern, '')) !== false) {
167
+			// capture split
168
+			$lengths[] = [$array[0] - $position, false, null];
169
+
170
+			// move position
171
+			$position = $array[0] + $array[1];
172
+
173
+			// capture delimiter
174
+			$regs = mb_ereg_search_getregs();
175
+			$lengths[] = [$array[1], true, isset($regs[1]) && $regs[1]];
176
+		}
177
+
178
+		// Add last bit, if not ending with split
179
+		$lengths[] = [$strlen - $position, false, null];
180
+
181
+		return $lengths;
182
+	}
183 183
 }
184 184
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -71,7 +71,7 @@
 block discarded – undo
71 71
      */
72 72
     public static function split($pattern, $string, $limit = -1, $flags = 0)
73 73
     {
74
-        $offset_capture = (bool)($flags & PREG_SPLIT_OFFSET_CAPTURE);
74
+        $offset_capture = (bool) ($flags & PREG_SPLIT_OFFSET_CAPTURE);
75 75
 
76 76
         $lengths = self::getSplitLengths($pattern, $string);
77 77
 
Please login to merge, or discard this patch.
src/Sentence.php 2 patches
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -75,7 +75,7 @@  discard block
 block discarded – undo
75 75
 
76 76
             $this->replacements[$index] = $number;
77 77
 
78
-            $text = (string)substr_replace($text, $code, $offset, mb_strlen($number));
78
+            $text = (string) substr_replace($text, $code, $offset, mb_strlen($number));
79 79
 
80 80
             ++$index;
81 81
         }
@@ -92,7 +92,7 @@  discard block
 block discarded – undo
92 92
      */
93 93
     private function restoreReplacements($text)
94 94
     {
95
-        return array_map(function ($value) {
95
+        return array_map(function($value) {
96 96
             foreach ($this->replacements as $index => $number) {
97 97
                 $code = $this->getReplaceCode($index);
98 98
                 $value = str_replace($code, $number, $value);
@@ -190,7 +190,7 @@  discard block
 block discarded – undo
190 190
         $merges = [];
191 191
         $merge = '';
192 192
 
193
-        $filtered = array_filter($punctuations, function ($p) {
193
+        $filtered = array_filter($punctuations, function($p) {
194 194
             return $p !== '';
195 195
         });
196 196
 
@@ -448,7 +448,7 @@  discard block
 block discarded – undo
448 448
      */
449 449
     private static function trimSentences($sentences)
450 450
     {
451
-        return array_map(function ($sentence) {
451
+        return array_map(function($sentence) {
452 452
             return Multibyte::trim($sentence);
453 453
         }, $sentences);
454 454
     }
Please login to merge, or discard this patch.
Indentation   +456 added lines, -456 removed lines patch added patch discarded remove patch
@@ -17,461 +17,461 @@
 block discarded – undo
17 17
 class Sentence
18 18
 {
19 19
 
20
-    /**
21
-     * Specify this flag with the split method to trim whitespace.
22
-     */
23
-    const SPLIT_TRIM = 0x1;
24
-
25
-    /**
26
-     * List of characters used to terminate sentences.
27
-     *
28
-     * @var string[]
29
-     */
30
-    private $terminals = ['.', '!', '?'];
31
-
32
-    /**
33
-     * List of characters used for abbreviations.
34
-     *
35
-     * @var string[]
36
-     */
37
-    private $abbreviators = ['.'];
38
-
39
-    /**
40
-     * List of replacements in the text.
41
-     *
42
-     * @var string[]
43
-     */
44
-    private $replacements = [];
45
-
46
-    /**
47
-     * Generate an in-text replacement code for the specified index
48
-     *
49
-     * @param int $index
50
-     *
51
-     * @return string
52
-     */
53
-    private function getReplaceCode(int $index)
54
-    {
55
-        return 0x02 . $index . 0x03;
56
-    }
57
-
58
-    /**
59
-     * Clean floating point numbers by replace them with an in-text index
60
-     *
61
-     * @param string $text
62
-     *
63
-     * @return string
64
-     */
65
-    private function replaceFloatNumbers(string $text)
66
-    {
67
-        preg_match_all('!\d+(?:\.\d+)?!', $text, $matches, PREG_OFFSET_CAPTURE);
68
-
69
-        $this->replacements = [];
70
-        $index = 0;
71
-        foreach (array_reverse($matches[0]) as $match) {
72
-            $number = $match[0];
73
-            $offset = $match[1];
74
-            $code = $this->getReplaceCode($index);
75
-
76
-            $this->replacements[$index] = $number;
77
-
78
-            $text = (string)substr_replace($text, $code, $offset, mb_strlen($number));
79
-
80
-            ++$index;
81
-        }
82
-
83
-        return $text;
84
-    }
85
-
86
-    /**
87
-     * Restore any stored replacements
88
-     *
89
-     * @param string[] $text
90
-     *
91
-     * @return string[]
92
-     */
93
-    private function restoreReplacements($text)
94
-    {
95
-        return array_map(function ($value) {
96
-            foreach ($this->replacements as $index => $number) {
97
-                $code = $this->getReplaceCode($index);
98
-                $value = str_replace($code, $number, $value);
99
-            }
100
-
101
-            return $value;
102
-        }, $text);
103
-    }
104
-
105
-    /**
106
-     * Breaks a piece of text into lines by linebreak.
107
-     * Eats up any linebreak characters as if one.
108
-     *
109
-     * Multibyte.php safe
110
-     *
111
-     * @param string $text
112
-     *
113
-     * @return string[]
114
-     */
115
-    private static function linebreakSplit($text)
116
-    {
117
-        $lines = [];
118
-        $line = '';
119
-
120
-        foreach (Multibyte::split('([\r\n]+)', $text, -1, PREG_SPLIT_DELIM_CAPTURE) as $part) {
121
-            $line .= $part;
122
-            if (Multibyte::trim($part) === '') {
123
-                $lines[] = $line;
124
-                $line = '';
125
-            }
126
-        }
127
-        $lines[] = $line;
128
-
129
-        return $lines;
130
-    }
131
-
132
-    /**
133
-     * Splits an array of lines by (consecutive sequences of)
134
-     * terminals, keeping terminals.
135
-     *
136
-     * Multibyte.php safe (atleast for UTF-8)
137
-     *
138
-     * For example:
139
-     *    "There ... is. More!"
140
-     *        ... becomes ...
141
-     *    [ "There ", "...", " is", ".", " More", "!" ]
142
-     *
143
-     * @param string $line
144
-     *
145
-     * @return string[]
146
-     */
147
-    private function punctuationSplit($line)
148
-    {
149
-        $parts = [];
150
-
151
-        $chars = preg_split('//u', $line, -1, PREG_SPLIT_NO_EMPTY); // This is UTF8 multibyte safe!
152
-        //add space after each terminal because every sentence ends with terminal and whitespace
153
-        $terminals = array_map(function($terminal)
154
-            {
155
-                return sprintf('%s ', $terminal);
156
-            },
157
-            $this->terminals
158
-        );
159
-        $is_terminal = in_array($chars[0], $terminals);
160
-
161
-        $part = '';
162
-        foreach ($chars as $key => $char) {
163
-            $nextChar = isset($chars[$key + 1]) ? $chars[$key + 1] : '';
164
-            $checkChar = sprintf('%s%s', $char, $nextChar); //try to find something like ". "
165
-            if (in_array($checkChar, $terminals) !== $is_terminal) {
166
-                $parts[] = $part;
167
-                $part = '';
168
-                $is_terminal = !$is_terminal;
169
-            }
170
-            $part .= $char;
171
-        }
172
-
173
-        if (!empty($part)) {
174
-            $parts[] = $part;
175
-        }
176
-
177
-        return $parts;
178
-    }
179
-
180
-    /**
181
-     * Appends each terminal item after it's preceding
182
-     * non-terminals.
183
-     *
184
-     * Multibyte.php safe (atleast for UTF-8)
185
-     *
186
-     * For example:
187
-     *    [ "There ", "...", " is", ".", " More", "!" ]
188
-     *        ... becomes ...
189
-     *    [ "There ... is.", "More!" ]
190
-     *
191
-     * @param string[] $punctuations
192
-     *
193
-     * @return string[]
194
-     */
195
-    private function punctuationMerge($punctuations)
196
-    {
197
-        $definite_terminals = array_diff($this->terminals, $this->abbreviators);
198
-
199
-        $merges = [];
200
-        $merge = '';
201
-
202
-        $filtered = array_filter($punctuations, function ($p) {
203
-            return $p !== '';
204
-        });
205
-
206
-        foreach ($filtered as $punctuation) {
207
-            $merge .= $punctuation;
208
-            if (mb_strlen($punctuation) === 1
209
-                && in_array($punctuation, $this->terminals)) {
210
-                $merges[] = $merge;
211
-                $merge = '';
212
-            } else {
213
-                foreach ($definite_terminals as $terminal) {
214
-                    if (mb_strpos($punctuation, $terminal) !== false) {
215
-                        $merges[] = $merge;
216
-                        $merge = '';
217
-                        break;
218
-                    }
219
-                }
220
-            }
221
-        }
222
-        if (!empty($merge)) {
223
-            $merges[] = $merge;
224
-        }
225
-
226
-        return $merges;
227
-    }
228
-
229
-    /**
230
-     * Looks for capitalized abbreviations & includes them with the following fragment.
231
-     *
232
-     * For example:
233
-     *    [ "Last week, former director of the F.B.I. James B. Comey was fired. Mr. Comey was not available for comment." ]
234
-     *        ... becomes ...
235
-     *    [ "Last week, former director of the F.B.I. James B. Comey was fired." ]
236
-     *  [ "Mr. Comey was not available for comment." ]
237
-     *
238
-     * @param string[] $fragments
239
-     *
240
-     * @return string[]
241
-     */
242
-    private function abbreviationMerge($fragments)
243
-    {
244
-        $return_fragment = [];
245
-
246
-        $previous_fragment = '';
247
-        $previous_is_abbreviation = false;
248
-        $i = 0;
249
-        foreach ($fragments as $fragment) {
250
-            $is_abbreviation = self::isAbreviation($fragment);
251
-
252
-            // merge previous fragment with this
253
-            if ($previous_is_abbreviation) {
254
-                $fragment = $previous_fragment . $fragment;
255
-            }
256
-            $return_fragment[$i] = $fragment;
257
-
258
-            $previous_is_abbreviation = $is_abbreviation;
259
-            $previous_fragment = $fragment;
260
-
261
-            // only increment if this isn't an abbreviation
262
-            if (!$is_abbreviation) {
263
-                $i++;
264
-            }
265
-        }
266
-
267
-        return $return_fragment;
268
-    }
269
-
270
-    /**
271
-     * Check if the last word of fragment starts with a Capital, ends in "." & has less than 3 characters.
272
-     *
273
-     * @param $fragment
274
-     *
275
-     * @return bool
276
-     */
277
-    private static function isAbreviation($fragment)
278
-    {
279
-        $words = mb_split('\s+', Multibyte::trim($fragment));
280
-
281
-        $word_count = count($words);
282
-
283
-        $last_word = Multibyte::trim($words[$word_count - 1]);
284
-        $last_is_capital = preg_match('#^\p{Lu}#u', $last_word);
285
-        $last_is_abbreviation = mb_substr(Multibyte::trim($fragment), -1) === '.';
286
-
287
-        return $last_is_capital > 0
288
-            && $last_is_abbreviation > 0
289
-            && mb_strlen($last_word) <= 3;
290
-    }
291
-
292
-    /**
293
-     * Merges any part starting with a closing parenthesis ')' to the previous
294
-     * part.
295
-     *
296
-     * @param string[] $parts
297
-     *
298
-     * @return string[]
299
-     */
300
-    private function parenthesesMerge($parts)
301
-    {
302
-        $subsentences = [];
303
-
304
-        foreach ($parts as $part) {
305
-            if ($part[0] === ')' && !empty($subsentences)) {
306
-                $subsentences[count($subsentences) - 1] .= $part;
307
-            } else {
308
-                $subsentences[] = $part;
309
-            }
310
-        }
311
-
312
-        return $subsentences;
313
-    }
314
-
315
-    /**
316
-     * Looks for closing quotes to include them with the previous statement.
317
-     * "That was very interesting," he said.
318
-     * "That was very interesting."
319
-     *
320
-     * @param string[] $statements
321
-     *
322
-     * @return string[]
323
-     */
324
-    private function closeQuotesMerge($statements)
325
-    {
326
-        $i = 0;
327
-        $previous_statement = '';
328
-        $return = [];
329
-        foreach ($statements as $statement) {
330
-            if (self::isEndQuote($statement)) {
331
-                $statement = $previous_statement . $statement;
332
-            } else {
333
-                $i++;
334
-            }
335
-
336
-            $return[$i] = $statement;
337
-            $previous_statement = $statement;
338
-        }
339
-
340
-        return $return;
341
-    }
342
-
343
-    /**
344
-     * Check if the entire string is a quotation mark or quote, then space, then lowercase.
345
-     *
346
-     * @param $statement
347
-     *
348
-     * @return bool
349
-     */
350
-    private static function isEndQuote($statement)
351
-    {
352
-        $trimmed = Multibyte::trim($statement);
353
-        $first = mb_substr($statement, 0, 1);
354
-
355
-        return in_array($trimmed, ['"', '\''])
356
-            || (
357
-                in_array($first, ['"', '\''])
358
-                && mb_substr($statement, 1, 1) === ' '
359
-                && ctype_lower(mb_substr($statement, 2, 1)) === true
360
-            );
361
-    }
362
-
363
-    /**
364
-     * Merges items into larger sentences.
365
-     * Multibyte.php safe
366
-     *
367
-     * @param string[] $shorts
368
-     *
369
-     * @return string[]
370
-     */
371
-    private function sentenceMerge($shorts)
372
-    {
373
-        $non_abbreviating_terminals = array_diff($this->terminals, $this->abbreviators);
374
-
375
-        $sentences = [];
376
-
377
-        $sentence = '';
378
-        $has_words = false;
379
-        $previous_word_ending = null;
380
-        foreach ($shorts as $short) {
381
-            $word_count = count(mb_split('\s+', Multibyte::trim($short)));
382
-            $after_non_abbreviating_terminal = in_array($previous_word_ending, $non_abbreviating_terminals);
383
-
384
-            if ($after_non_abbreviating_terminal
385
-                || ($has_words && $word_count > 1)) {
386
-
387
-                $sentences[] = $sentence;
388
-
389
-                $sentence = '';
390
-                $has_words = false;
391
-            }
392
-
393
-            $has_words = $has_words
394
-                || $word_count > 1;
395
-
396
-            $sentence .= $short;
397
-            $previous_word_ending = mb_substr($short, -1);
398
-        }
399
-
400
-        if (!empty($sentence)) {
401
-            $sentences[] = $sentence;
402
-        }
403
-
404
-        return $sentences;
405
-    }
406
-
407
-    /**
408
-     * Return the sentences sentences detected in the provided text.
409
-     * Set the Sentence::SPLIT_TRIM flag to trim whitespace.
410
-     *
411
-     * @param string  $text
412
-     * @param integer $flags
413
-     *
414
-     * @return string[]
415
-     */
416
-    public function split($text, $flags = 0)
417
-    {
418
-        static $pipeline = [
419
-            'replaceFloatNumbers',
420
-            'punctuationSplit',
421
-            'parenthesesMerge', // also works after punctuationMerge or abbreviationMerge
422
-            'punctuationMerge',
423
-            'abbreviationMerge',
424
-            'closeQuotesMerge',
425
-            'sentenceMerge',
426
-            'restoreReplacements',
427
-        ];
428
-
429
-        // clean funny quotes
430
-        $text = Multibyte::cleanUnicode($text);
431
-
432
-        // Split
433
-        $sentences = [];
434
-        foreach (self::linebreakSplit($text) as $input) {
435
-            if (Multibyte::trim($input) !== '') {
436
-                foreach ($pipeline as $method) {
437
-                    $input = $this->$method($input);
438
-                }
439
-                $sentences = array_merge($sentences, $input);
440
-            }
441
-        }
442
-
443
-        // Post process
444
-        if ($flags & self::SPLIT_TRIM) {
445
-            return self::trimSentences($sentences);
446
-        }
447
-
448
-        return $sentences;
449
-    }
450
-
451
-    /**
452
-     * Multibyte.php trim each string in an array.
453
-     *
454
-     * @param string[] $sentences
455
-     *
456
-     * @return string[]
457
-     */
458
-    private static function trimSentences($sentences)
459
-    {
460
-        return array_map(function ($sentence) {
461
-            return Multibyte::trim($sentence);
462
-        }, $sentences);
463
-    }
464
-
465
-    /**
466
-     * Return the number of sentences detected in the provided text.
467
-     *
468
-     * @param string $text
469
-     *
470
-     * @return integer
471
-     */
472
-    public function count($text)
473
-    {
474
-        return count($this->split($text));
475
-    }
20
+	/**
21
+	 * Specify this flag with the split method to trim whitespace.
22
+	 */
23
+	const SPLIT_TRIM = 0x1;
24
+
25
+	/**
26
+	 * List of characters used to terminate sentences.
27
+	 *
28
+	 * @var string[]
29
+	 */
30
+	private $terminals = ['.', '!', '?'];
31
+
32
+	/**
33
+	 * List of characters used for abbreviations.
34
+	 *
35
+	 * @var string[]
36
+	 */
37
+	private $abbreviators = ['.'];
38
+
39
+	/**
40
+	 * List of replacements in the text.
41
+	 *
42
+	 * @var string[]
43
+	 */
44
+	private $replacements = [];
45
+
46
+	/**
47
+	 * Generate an in-text replacement code for the specified index
48
+	 *
49
+	 * @param int $index
50
+	 *
51
+	 * @return string
52
+	 */
53
+	private function getReplaceCode(int $index)
54
+	{
55
+		return 0x02 . $index . 0x03;
56
+	}
57
+
58
+	/**
59
+	 * Clean floating point numbers by replace them with an in-text index
60
+	 *
61
+	 * @param string $text
62
+	 *
63
+	 * @return string
64
+	 */
65
+	private function replaceFloatNumbers(string $text)
66
+	{
67
+		preg_match_all('!\d+(?:\.\d+)?!', $text, $matches, PREG_OFFSET_CAPTURE);
68
+
69
+		$this->replacements = [];
70
+		$index = 0;
71
+		foreach (array_reverse($matches[0]) as $match) {
72
+			$number = $match[0];
73
+			$offset = $match[1];
74
+			$code = $this->getReplaceCode($index);
75
+
76
+			$this->replacements[$index] = $number;
77
+
78
+			$text = (string)substr_replace($text, $code, $offset, mb_strlen($number));
79
+
80
+			++$index;
81
+		}
82
+
83
+		return $text;
84
+	}
85
+
86
+	/**
87
+	 * Restore any stored replacements
88
+	 *
89
+	 * @param string[] $text
90
+	 *
91
+	 * @return string[]
92
+	 */
93
+	private function restoreReplacements($text)
94
+	{
95
+		return array_map(function ($value) {
96
+			foreach ($this->replacements as $index => $number) {
97
+				$code = $this->getReplaceCode($index);
98
+				$value = str_replace($code, $number, $value);
99
+			}
100
+
101
+			return $value;
102
+		}, $text);
103
+	}
104
+
105
+	/**
106
+	 * Breaks a piece of text into lines by linebreak.
107
+	 * Eats up any linebreak characters as if one.
108
+	 *
109
+	 * Multibyte.php safe
110
+	 *
111
+	 * @param string $text
112
+	 *
113
+	 * @return string[]
114
+	 */
115
+	private static function linebreakSplit($text)
116
+	{
117
+		$lines = [];
118
+		$line = '';
119
+
120
+		foreach (Multibyte::split('([\r\n]+)', $text, -1, PREG_SPLIT_DELIM_CAPTURE) as $part) {
121
+			$line .= $part;
122
+			if (Multibyte::trim($part) === '') {
123
+				$lines[] = $line;
124
+				$line = '';
125
+			}
126
+		}
127
+		$lines[] = $line;
128
+
129
+		return $lines;
130
+	}
131
+
132
+	/**
133
+	 * Splits an array of lines by (consecutive sequences of)
134
+	 * terminals, keeping terminals.
135
+	 *
136
+	 * Multibyte.php safe (atleast for UTF-8)
137
+	 *
138
+	 * For example:
139
+	 *    "There ... is. More!"
140
+	 *        ... becomes ...
141
+	 *    [ "There ", "...", " is", ".", " More", "!" ]
142
+	 *
143
+	 * @param string $line
144
+	 *
145
+	 * @return string[]
146
+	 */
147
+	private function punctuationSplit($line)
148
+	{
149
+		$parts = [];
150
+
151
+		$chars = preg_split('//u', $line, -1, PREG_SPLIT_NO_EMPTY); // This is UTF8 multibyte safe!
152
+		//add space after each terminal because every sentence ends with terminal and whitespace
153
+		$terminals = array_map(function($terminal)
154
+			{
155
+				return sprintf('%s ', $terminal);
156
+			},
157
+			$this->terminals
158
+		);
159
+		$is_terminal = in_array($chars[0], $terminals);
160
+
161
+		$part = '';
162
+		foreach ($chars as $key => $char) {
163
+			$nextChar = isset($chars[$key + 1]) ? $chars[$key + 1] : '';
164
+			$checkChar = sprintf('%s%s', $char, $nextChar); //try to find something like ". "
165
+			if (in_array($checkChar, $terminals) !== $is_terminal) {
166
+				$parts[] = $part;
167
+				$part = '';
168
+				$is_terminal = !$is_terminal;
169
+			}
170
+			$part .= $char;
171
+		}
172
+
173
+		if (!empty($part)) {
174
+			$parts[] = $part;
175
+		}
176
+
177
+		return $parts;
178
+	}
179
+
180
+	/**
181
+	 * Appends each terminal item after it's preceding
182
+	 * non-terminals.
183
+	 *
184
+	 * Multibyte.php safe (atleast for UTF-8)
185
+	 *
186
+	 * For example:
187
+	 *    [ "There ", "...", " is", ".", " More", "!" ]
188
+	 *        ... becomes ...
189
+	 *    [ "There ... is.", "More!" ]
190
+	 *
191
+	 * @param string[] $punctuations
192
+	 *
193
+	 * @return string[]
194
+	 */
195
+	private function punctuationMerge($punctuations)
196
+	{
197
+		$definite_terminals = array_diff($this->terminals, $this->abbreviators);
198
+
199
+		$merges = [];
200
+		$merge = '';
201
+
202
+		$filtered = array_filter($punctuations, function ($p) {
203
+			return $p !== '';
204
+		});
205
+
206
+		foreach ($filtered as $punctuation) {
207
+			$merge .= $punctuation;
208
+			if (mb_strlen($punctuation) === 1
209
+				&& in_array($punctuation, $this->terminals)) {
210
+				$merges[] = $merge;
211
+				$merge = '';
212
+			} else {
213
+				foreach ($definite_terminals as $terminal) {
214
+					if (mb_strpos($punctuation, $terminal) !== false) {
215
+						$merges[] = $merge;
216
+						$merge = '';
217
+						break;
218
+					}
219
+				}
220
+			}
221
+		}
222
+		if (!empty($merge)) {
223
+			$merges[] = $merge;
224
+		}
225
+
226
+		return $merges;
227
+	}
228
+
229
+	/**
230
+	 * Looks for capitalized abbreviations & includes them with the following fragment.
231
+	 *
232
+	 * For example:
233
+	 *    [ "Last week, former director of the F.B.I. James B. Comey was fired. Mr. Comey was not available for comment." ]
234
+	 *        ... becomes ...
235
+	 *    [ "Last week, former director of the F.B.I. James B. Comey was fired." ]
236
+	 *  [ "Mr. Comey was not available for comment." ]
237
+	 *
238
+	 * @param string[] $fragments
239
+	 *
240
+	 * @return string[]
241
+	 */
242
+	private function abbreviationMerge($fragments)
243
+	{
244
+		$return_fragment = [];
245
+
246
+		$previous_fragment = '';
247
+		$previous_is_abbreviation = false;
248
+		$i = 0;
249
+		foreach ($fragments as $fragment) {
250
+			$is_abbreviation = self::isAbreviation($fragment);
251
+
252
+			// merge previous fragment with this
253
+			if ($previous_is_abbreviation) {
254
+				$fragment = $previous_fragment . $fragment;
255
+			}
256
+			$return_fragment[$i] = $fragment;
257
+
258
+			$previous_is_abbreviation = $is_abbreviation;
259
+			$previous_fragment = $fragment;
260
+
261
+			// only increment if this isn't an abbreviation
262
+			if (!$is_abbreviation) {
263
+				$i++;
264
+			}
265
+		}
266
+
267
+		return $return_fragment;
268
+	}
269
+
270
+	/**
271
+	 * Check if the last word of fragment starts with a Capital, ends in "." & has less than 3 characters.
272
+	 *
273
+	 * @param $fragment
274
+	 *
275
+	 * @return bool
276
+	 */
277
+	private static function isAbreviation($fragment)
278
+	{
279
+		$words = mb_split('\s+', Multibyte::trim($fragment));
280
+
281
+		$word_count = count($words);
282
+
283
+		$last_word = Multibyte::trim($words[$word_count - 1]);
284
+		$last_is_capital = preg_match('#^\p{Lu}#u', $last_word);
285
+		$last_is_abbreviation = mb_substr(Multibyte::trim($fragment), -1) === '.';
286
+
287
+		return $last_is_capital > 0
288
+			&& $last_is_abbreviation > 0
289
+			&& mb_strlen($last_word) <= 3;
290
+	}
291
+
292
+	/**
293
+	 * Merges any part starting with a closing parenthesis ')' to the previous
294
+	 * part.
295
+	 *
296
+	 * @param string[] $parts
297
+	 *
298
+	 * @return string[]
299
+	 */
300
+	private function parenthesesMerge($parts)
301
+	{
302
+		$subsentences = [];
303
+
304
+		foreach ($parts as $part) {
305
+			if ($part[0] === ')' && !empty($subsentences)) {
306
+				$subsentences[count($subsentences) - 1] .= $part;
307
+			} else {
308
+				$subsentences[] = $part;
309
+			}
310
+		}
311
+
312
+		return $subsentences;
313
+	}
314
+
315
+	/**
316
+	 * Looks for closing quotes to include them with the previous statement.
317
+	 * "That was very interesting," he said.
318
+	 * "That was very interesting."
319
+	 *
320
+	 * @param string[] $statements
321
+	 *
322
+	 * @return string[]
323
+	 */
324
+	private function closeQuotesMerge($statements)
325
+	{
326
+		$i = 0;
327
+		$previous_statement = '';
328
+		$return = [];
329
+		foreach ($statements as $statement) {
330
+			if (self::isEndQuote($statement)) {
331
+				$statement = $previous_statement . $statement;
332
+			} else {
333
+				$i++;
334
+			}
335
+
336
+			$return[$i] = $statement;
337
+			$previous_statement = $statement;
338
+		}
339
+
340
+		return $return;
341
+	}
342
+
343
+	/**
344
+	 * Check if the entire string is a quotation mark or quote, then space, then lowercase.
345
+	 *
346
+	 * @param $statement
347
+	 *
348
+	 * @return bool
349
+	 */
350
+	private static function isEndQuote($statement)
351
+	{
352
+		$trimmed = Multibyte::trim($statement);
353
+		$first = mb_substr($statement, 0, 1);
354
+
355
+		return in_array($trimmed, ['"', '\''])
356
+			|| (
357
+				in_array($first, ['"', '\''])
358
+				&& mb_substr($statement, 1, 1) === ' '
359
+				&& ctype_lower(mb_substr($statement, 2, 1)) === true
360
+			);
361
+	}
362
+
363
+	/**
364
+	 * Merges items into larger sentences.
365
+	 * Multibyte.php safe
366
+	 *
367
+	 * @param string[] $shorts
368
+	 *
369
+	 * @return string[]
370
+	 */
371
+	private function sentenceMerge($shorts)
372
+	{
373
+		$non_abbreviating_terminals = array_diff($this->terminals, $this->abbreviators);
374
+
375
+		$sentences = [];
376
+
377
+		$sentence = '';
378
+		$has_words = false;
379
+		$previous_word_ending = null;
380
+		foreach ($shorts as $short) {
381
+			$word_count = count(mb_split('\s+', Multibyte::trim($short)));
382
+			$after_non_abbreviating_terminal = in_array($previous_word_ending, $non_abbreviating_terminals);
383
+
384
+			if ($after_non_abbreviating_terminal
385
+				|| ($has_words && $word_count > 1)) {
386
+
387
+				$sentences[] = $sentence;
388
+
389
+				$sentence = '';
390
+				$has_words = false;
391
+			}
392
+
393
+			$has_words = $has_words
394
+				|| $word_count > 1;
395
+
396
+			$sentence .= $short;
397
+			$previous_word_ending = mb_substr($short, -1);
398
+		}
399
+
400
+		if (!empty($sentence)) {
401
+			$sentences[] = $sentence;
402
+		}
403
+
404
+		return $sentences;
405
+	}
406
+
407
+	/**
408
+	 * Return the sentences sentences detected in the provided text.
409
+	 * Set the Sentence::SPLIT_TRIM flag to trim whitespace.
410
+	 *
411
+	 * @param string  $text
412
+	 * @param integer $flags
413
+	 *
414
+	 * @return string[]
415
+	 */
416
+	public function split($text, $flags = 0)
417
+	{
418
+		static $pipeline = [
419
+			'replaceFloatNumbers',
420
+			'punctuationSplit',
421
+			'parenthesesMerge', // also works after punctuationMerge or abbreviationMerge
422
+			'punctuationMerge',
423
+			'abbreviationMerge',
424
+			'closeQuotesMerge',
425
+			'sentenceMerge',
426
+			'restoreReplacements',
427
+		];
428
+
429
+		// clean funny quotes
430
+		$text = Multibyte::cleanUnicode($text);
431
+
432
+		// Split
433
+		$sentences = [];
434
+		foreach (self::linebreakSplit($text) as $input) {
435
+			if (Multibyte::trim($input) !== '') {
436
+				foreach ($pipeline as $method) {
437
+					$input = $this->$method($input);
438
+				}
439
+				$sentences = array_merge($sentences, $input);
440
+			}
441
+		}
442
+
443
+		// Post process
444
+		if ($flags & self::SPLIT_TRIM) {
445
+			return self::trimSentences($sentences);
446
+		}
447
+
448
+		return $sentences;
449
+	}
450
+
451
+	/**
452
+	 * Multibyte.php trim each string in an array.
453
+	 *
454
+	 * @param string[] $sentences
455
+	 *
456
+	 * @return string[]
457
+	 */
458
+	private static function trimSentences($sentences)
459
+	{
460
+		return array_map(function ($sentence) {
461
+			return Multibyte::trim($sentence);
462
+		}, $sentences);
463
+	}
464
+
465
+	/**
466
+	 * Return the number of sentences detected in the provided text.
467
+	 *
468
+	 * @param string $text
469
+	 *
470
+	 * @return integer
471
+	 */
472
+	public function count($text)
473
+	{
474
+		return count($this->split($text));
475
+	}
476 476
 
477 477
 }
Please login to merge, or discard this patch.