查詢

IntlRuleBasedBreakIterator::__construct()函式—用法及示例

「 建立一個新的 IntlRuleBasedBreakIterator 物件 」


函式名:IntlRuleBasedBreakIterator::__construct()

適用版本:PHP 7.0.0 及以上版本

用法:IntlRuleBasedBreakIterator::__construct() 函式用於建立一個新的 IntlRuleBasedBreakIterator 物件。

引數:

  • $rules:一個包含規則的字串,用於定義斷句規則。規則字串必須符合 Unicode Text Segmentation 標準,可以使用 ICU Rule Syntax。
  • $breakType:可選引數,指定斷句的型別。可以是以下常量之一:
    • IntlRuleBasedBreakIterator::BREAK_TYPE_WORD:按單詞斷句。
    • IntlRuleBasedBreakIterator::BREAK_TYPE_LINE:按行斷句。
    • IntlRuleBasedBreakIterator::BREAK_TYPE_SENTENCE:按句子斷句。
    • IntlRuleBasedBreakIterator::BREAK_TYPE_TITLE:按標題斷句。

返回值:返回一個新的 IntlRuleBasedBreakIterator 物件。

示例:

$rules = <<<RULES
    !forward;
    \p{Z} & !\p{Zs} & !\p{Zl} & !\p{Zp} {rule_break: true};
RULES;

$breakIterator = new IntlRuleBasedBreakIterator($rules, IntlRuleBasedBreakIterator::BREAK_TYPE_SENTENCE);

$text = "This is a sample sentence. It demonstrates the usage of IntlRuleBasedBreakIterator.";

$breakIterator->setText($text);

foreach ($breakIterator as $boundary) {
    echo substr($text, $boundary[0], $boundary[1] - $boundary[0]) . PHP_EOL;
}

在上面的示例中,我們首先定義了一個包含斷句規則的字串。然後,我們使用 IntlRuleBasedBreakIterator::__construct() 函式建立了一個 IntlRuleBasedBreakIterator 物件,並指定斷句型別為 IntlRuleBasedBreakIterator::BREAK_TYPE_SENTENCE。接下來,我們使用 setText() 函式設定要斷句的文字。最後,我們使用 foreach 迴圈遍歷斷句邊界,並列印出每個斷句的內容。輸出結果如下:

This is a sample sentence.
 It demonstrates the usage of IntlRuleBasedBreakIterator.
補充糾錯
熱門PHP函式
分享連結