如何在PHP中拆分多个连接词



示例字符串:"outofthebox">

我想得到这样的输出:Array ( [0] => out [1] => of [2] => the [3] => box )

我现在得到什么:Array ( [0] => out [1] => oft [2] => heb [3] => ox )

我不知道这怎么可能。我需要那种逻辑,怎样才能得到更有意义的结果。

我基于这个https://stackoverflow.com/a/481773/17035224 Python答案在PHP上构建它。但是我不擅长Python。在这个python脚本中,它返回的结果正是我想要的。另一个名为"wordninja"的python脚本也工作得很好。

我的PHP脚本:
<?php
$db = new PDO("mysql:host=localhost;dbname=strings", "root", "");
$text = "outofthebox";
$finish = false;
$words = [];
$find = false;
$start = -1;
$added = false;
$comp = [];
for($i = 0; $i<strlen($text); $i++) {
if(count($words) > 0) {
$last = max($words);
$comp[] = $last;
$words = [];
$start = strlen(implode("", $comp));
if($added === true) {
$added = false;
}else {
$start++;
}
}else {
$start++;
}
$part = "";
for($j = $start; $j<strlen($text); $j++) {
$part .= $text[$j];
echo $part."<br>";
$check = checkWord($part);
if($check === true) {
$added = true;
$words[] = $part;
}
}
}
print_r($comp);
function checkWord($text) {
global $db;
$check = $db->query("select * from strings where string='".$text."'")->fetch(PDO::FETCH_ASSOC);
if(isset($check["id"]) == true) {
return true;
}
return false;
}

其他不同之处在于我使用mysql数据库作为字典,而不是txt。

如果将checkWord函数更改为:

function checkWord($text) {

$arr = [
'out',
'of',
'the',
'box',
];
if(in_array($text, $arr)) {
return true;
}

return false;
}

你会发现结果将是:

Array ( [0] => out [1] => of [2] => the [3] => box )

所以我猜你的查询有假阳性,检查一下,你就能解决问题了。

最新更新