2012-09-30 49 views
2

這是我試圖獲得的內容: My longest text to test當我搜索例如My我應該得到My longest獲取當前字符串中的下一個單詞

我試着用這個函數首先得到輸入的完整長度,然後搜索''來剪切它。

$length = strripos($text, $input) + strlen($input)+2;

$stringpos = strripos($text, ' ', $length);

$newstring = substr($text, 0, strpos($text, ' ', $length));

但是這僅適用第一次,然後它的電流輸入後削減,意味着 My lonMy longest而不是My longest text

我該如何改變這個才能獲得正確的結果,總是會得到下一個單詞。也許我需要休息一下,但我找不到合適的解決方案。

UPDATE

這裏是我的解決辦法,直到我找到一個更好的解決方案。正如我所說的使用數組函數不起作用,因爲部分詞應該工作。所以我延續了我之前的想法。第一次和下一次的基本想法是不同的。我改進了一下代碼。

function get_title($input, $text) { 
    $length  = strripos($text, $input) + strlen($input); 
$stringpos = stripos($text, ' ', $length); 
// Find next ' ' 
$stringpos2 = stripos($text, ' ', $stringpos+1); 

if (!$stringpos) { 
    $newstring = $text; 
} else if ($stringpos2) { 
    $newstring = substr($text, 0, $stringpos2); 
} }  

不漂亮,但嘿它似乎工作^^。無論如何,也許你的某個人有更好的解決方案。

+0

假陽性怎麼樣,你可能在這個短語中有(說)'Mycoplasm',而沒有實際的單詞'My'? –

回答

3

您可以嘗試使用explode

$string = explode(" ", "My longest text to test"); 
$key = array_search("My", $string); 
echo $string[$key] , " " , $string[$key + 1] ; 

可以使用大小寫不敏感帶我到一個新的水平preg_match_all

$string = "My longest text to test in my school that is very close to mY village" ; 
var_dump(__search("My",$string)); 

輸出

array 
    0 => string 'My longest' (length=10) 
    1 => string 'my school' (length=9) 
    2 => string 'mY village' (length=10) 

功能使用

function __search($search,$string) 
{ 
    $result = array(); 
    preg_match_all('/' . preg_quote($search) . '\s+\w+/i', $string, $result); 
    return $result[0]; 
} 
+0

是的,這可行,但陣列解決方案的一大問題是,您無法搜索例如'我的學校'。那麼你沒有得到一個匹配的關鍵,所以這隻適用於單個單詞。但是謝謝你的想法。 –

+0

@Ruven JR。馬爾鬆見你的想法更新版本 – Baba

+0

你好巴巴thx。我試過你的代碼,但它只適用於整個單詞。我認爲處理的唯一方法是使用字符串函數。但是從現在起我還沒有100%的解決方案。 –

2

一個簡單的方法是將其分割上的空白,抓住當前數組索引加上下一個:

// Word to search for: 
$findme = "text"; 

// Using preg_split() to split on any amount of whitespace 
// lowercasing the words, to make the search case-insensitive 
$words = preg_split('/\s+/', "My longest text to test"); 

// Find the word in the array with array_search() 
// calling strtolower() with array_map() to search case-insensitively 
$idx = array_search(strtolower($findme), array_map('strtolower', $words)); 

if ($idx !== FALSE) { 
    // If found, print the word and the following word from the array 
    // as long as the following one exists. 
    echo $words[$idx]; 
    if (isset($words[$idx + 1])) { 
    echo " " . $words[$idx + 1]; 
    } 
} 

// Prints: 
// "text to" 
+0

與巴巴一樣,這隻適用於一個完整的單詞,而不是它的一部分。我認爲通過數組搜索不會在這裏工作或不這樣。 –

2

有更簡單的方法來做到這一點。如果你不想查找特定的東西,但是刪除預定義的東西長度,字符串函數很有用。否則,使用正則表達式:

preg_match('/My\s+\w+/', $string, $result); 

print $result[0]; 

這裏My查找文字第一個單詞。和\s+的一些空間。而\w+匹配單詞字符。

這增加了一些新的語法學習。但比變通辦法和更長的字符串函數代碼更脆弱,以實現相同。

+0

我知道有時preg_match是更好的解決方案,但我有我的問題來了解它^^,甚至很難閱讀一些關於它的網站。搜索到的輸入在哪裏? –

相關問題