2011-04-15 133 views
0

我試圖編寫一個基本上從句子中獲取「屬性」的函數。這些是參數。將此僞代碼翻譯成PHP

$q = "this apple is of red color"; OR $q = "this orange is of orange color"; 
$start = array('this apple', 'this orange'); 
$end = array('color', 'color'); 

,這是我努力使功能:

function prop($q, $start, $end) 
{ 
    /* 
    if $q (the sentence) starts with any of the $start 
    and/or ends with any of the end 
    separate to get "is of red" 
    */ 

} 

與代碼本身不僅我會遇到的問題,我也不知道如何進行搜索,如果任何數組值開始於(不僅包含)所提供的$ q。

任何輸入都會有幫助。 謝謝

+0

這種作業的氣味。它應該被標記,如果是這樣的話...... – Endophage 2011-04-16 00:14:21

+0

@Endophahge不會。我真的很想知道如何翻譯。 @ Wh1T3h4Ck5謝謝!會做! – Kartik 2011-04-16 04:24:59

回答

1

像這樣的東西應該工作

function prop($q, $start, $end) { 
    foreach ($start as $id=>$keyword) { 
    $res = false; 
    if ((strpos($q, $keyword) === 0) && (strrpos($q, $end[$id]) === strlen($q) - strlen($end[$id]))) { 
     $res = trim(str_replace($end[$id], '', str_replace($keyword, '', $q))); 
     break; 
     } 
    } 
    return $res; 
    } 

所以你的情況這個代碼

$q = "this orange is of orange color"; 
echo prop($q, $start, $end); 

打印

是橙色

這個鱈魚Ë

$q = "this apple is of red color"; 
echo prop($q, $start, $end); 

打印

是紅色

此代碼

$start = array('this apple', 'this orange', 'my dog'); 
$end = array('color', 'color', 'dog'); 

$q = "my dog is the best dog"; 
echo prop($q, $start, $end); 

將返回

是最好的

0

使用strposstrrpos。如果它們返回0,則字符串位於開始/結束處。

不是說你必須使用=== 0(或!== 0的倒數)來測試,因爲他們返回false如果字符串沒有被發現和0 == false0 !== false

+0

嗨,那麼開始代碼怎麼樣?我想'foreach($ start as $ testvalue){if(strpos($ q,$ testvalue)=== 0){...}}'。我想這會照顧開始的術語,但是如何將這個foreach循環的最後一個術語的測試合併到一起呢? – Kartik 2011-04-15 23:51:43