簡體   English   中英

使用PHP在沒有空格的字符串中查找單詞

[英]Use PHP to Find Words in a String Without Spaces

我正在尋找一個php庫,該庫可用於接收“ happyeaster”或“ buyaboat”之類的字符串,並返回各個單詞-“ happy”和“ easter”或“ buy”“ a”“ boat”。 有人知道現有的庫或已經建立的可以下載或購買的東西嗎?

我最終以這個腳本http://squarecog.wordpress.com/2008/10/19/splitting-words-joined-into-a-single-string/並在PHP中重做了。 我也接受最少字數的第一個解決方案。

如果不先告訴php,php將無法知道您要查找的單詞。

因此您可能需要多花一些精力來嘗試獲得有價值的答案。

您也許可以使用reg ex並找到要查找的單詞數組,或者使用substr。

例如,php怎么會知道您要在該字符串中找到單詞“ happy and Easter”和“ east”呢?

聽起來像您需要全文搜索庫。 嘗試使用Lucene和Zend Lucene庫。 希望能有所幫助。

<?php
function binary_search($elem, $array) { 
   $top = sizeof($array) -1; 
   $bot = 0; 

   while($top >= $bot) { 
      $p = floor(($top + $bot) / 2); 
      if ($array[$p] < $elem) 
        $bot = $p + 1; 
      elseif ($array[$p] > $elem) 
        $top = $p - 1; 
      else 
        return TRUE; 
   } 
   return FALSE; 
} 

$handle = @fopen("/usr/share/dict/words", "r");
if ($handle) {
    while (($buffer = fgets($handle, 4096)) !== false) {
        $words[] = trim($buffer);
    }
  fclose($handle);
}

sort($words);

function getmultiplewords($word1, $word2, &$dict){
    if (strlen($word1)==0) return;
    if (binary_search($word1, $dict) && binary_search($word2, $dict)) {
        echo $word2 . " / " . $word1. "\n";
    } 
    $word2 = $word2 . substr($word1,0,1);
    $word1 = substr($word1,1);
    getmultiplewords($word1, $word2, $dict);
}


getmultiplewords("cartalk","", $words);
getmultiplewords("superman","", $words);
?>

這是一個簡單的解決方案,它查找2個單詞的單詞。

它在帶有/ usr / share / dict / words文件的linux上工作,否則您必須在這里自己下載文件:

http://www.freebsd.org/cgi/cvsweb.cgi/src/share/dict/web2?rev=1.12;content-type=text%2Fplain

如果您想要n個單詞拆分,也可以對大小合適的單詞進行拆分:)請讓我知道,我會調查一下。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM