我正在尝试将文本拆分为单词:

$delimiterList = array(" ", ".", "-", ",", ";", "_", ":",
           "!", "?", "/", "(", ")", "[", "]", "{", "}", "<", ">", "\r", "\n",
           '"');
$words = mb_split($delimiterList, $string);

使用字符串工作得很好,但在某些我需要处理数字的情况下我会陷入困境。

E.g。如果我有文字“看看这个。我的分数是3.14,我很高兴。” 现在数组是

[0]=>Look,
[1]=>at,
[2]=>this,
[3]=>My,
[4]=>score,
[5]=>is,
[6]=>3,
[7]=>14,
[8]=>and, ....

然后3.14分为3和14,这在我的情况下不应该发生。 我的意思是点应分两个字符串而不是两个数字。 应该是这样的:

[0]=>Look,
[1]=>at,
[2]=>this,
[3]=>My,
[4]=>score,
[5]=>is,
[6]=>3.14,
[7]=>and, ....

但我不知道如何避免这种情况!

有人知道如何解决这个问题吗?

感谢名单, 花岗岩

有帮助吗?

解决方案

或者使用正则表达式:)

<?php
$str = "Look at this.My score is 3.14, and I am happy about it.";

// alternative to handle Marko's example (updated)
// /([\s_;?!\/\(\)\[\]{}<>\r\n"]|\.$|(?<=\D)[:,.\-]|[:,.\-](?=\D))/

var_dump(preg_split('/([\s\-_,:;?!\/\(\)\[\]{}<>\r\n"]|(?<!\d)\.(?!\d))/',
                    $str, null, PREG_SPLIT_NO_EMPTY));

array(13) {
  [0]=>
  string(4) "Look"
  [1]=>
  string(2) "at"
  [2]=>
  string(4) "this"
  [3]=>
  string(2) "My"
  [4]=>
  string(5) "score"
  [5]=>
  string(2) "is"
  [6]=>
  string(4) "3.14"
  [7]=>
  string(3) "and"
  [8]=>
  string(1) "I"
  [9]=>
  string(2) "am"
  [10]=>
  string(5) "happy"
  [11]=>
  string(5) "about"
  [12]=>
  string(2) "it"
}

其他提示

查看 strtok 。它允许您动态更改解析令牌,因此您可以在while循环中手动拆分字符串,将每个拆分字推入数组。

我的第一个想法是 preg_match_all('/ \ w + /',$ string,$ matches); 但是它给出的结果与你得到的结果相似。问题是用点分隔的数字非常模糊。它可以表示小数点和句子结尾,所以我们需要一种方法来改变字符串,以消除双重含义。

例如,在这句话中,我们有几个部分,我们想保留为一个词:&quot;看看这个。我的分数是3.14,我很高兴。它不是334,3而今天不是2009-12-12 11:12:13。“

我们首先构建一个search-&gt;替换词典,将异常编码为不会被分割的东西:

$encode = array(
    '/(\d+?)\.(\d+?)/' => '\\1DOT\\2',
    '/(\d+?),(\d+?)/' => '\\1COMMA\\2',
    '/(\d+?)-(\d+?)-(\d+?) (\d+?):(\d+?):(\d+?)/' => '\\1DASH\\2DASH\\3SPACE\\4COLON\\5COLON\\6'
);

接下来,我们对异常进行编码:

foreach ($encode as $regex => $repl) {
    $string = preg_replace($regex, $repl, $string);
}

拆分字符串:

preg_match_all('/\w+/', $string, $matches);

然后将编码后的单词转换回来:

$decode = array(
    'search' =>  array('DOT', 'COMMA', 'DASH', 'SPACE', 'COLON'),
    'replace' => array('.',   ',',     '-',    ' ',     ':'    )
);
foreach ($matches as $k => $v) {
    $matches[$k] = str_replace($decode['search'], $decode['replace'], $v);
}

$ matches 现在包含原始句子,该句子被分成具有正确例外的单词。

您可以将异常中使用的正则表达式设置为简单或复杂,但有些歧义总是会通过,例如两个结尾,第一个结束,下一个以数字开头:计数的数量应仅为3.3,除了3.5之外什么都没有。

使用&quot;。 <,代替&quot;。&quot;, in $ delimiterList

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top