2012-07-20 42 views
-3

我有一個典型的問題,我不確定它是否可能。我有一個領域是生產者的形式。我怎麼有可能,如果用戶使用這個詞在該領域再插入字在結果,如果用戶沒有在該領域用字然後插入字的結果。讓我以一個例子來解釋你。

實施例(字是在現場),那麼產生下面的結果:

ABC DEF 的電影的生產者。

實施例(字不處於字段),那麼產生下面的結果:

XYZ 電影的製片。

我有以下代碼:

if(!empty($_POST['Producer'])) { 
$description .= ' ' . $_POST["Producer"] . ' is/are the producer(s) of the movie'; 
} 

請告訴我,如果任何人有這個想法。

+1

看起來很簡單,你有什麼嘗試? – 2012-07-20 16:32:50

回答

2
if(!empty($_POST['Producer'])) 
{ 
    if(stripos($_POST['Producer'], ' and ') != false) // ' and ' is found 
     $producers = $_POST['Producer'] .' are the producers '; 
    else 
     $producers = $_POST['Producer'] .' is the producer '; 

    $description = $producers .'of the movie'; 
} 

我把' and ',而不是'and'(含空格),因爲一些名字包含單詞「是」,所以即使只有一個名字,將返回true。

+0

Isn'有可能使用**(!empty ** with **(strpos **?),因爲如果Producer的字段留空,那麼它不應該顯示整行。 – atif 2012-07-20 16:46:03

+0

@atif我編輯了我的答案,帶一個 – 2012-07-20 16:48:32

+0

非常重要的一點,在@Bandic00t的答案:它應該是''和''與空間,以防止匹配'布蘭德森'等...進一步,考慮使用strtolower()匹配'和', 'AND'... – cypherabe 2012-07-20 16:54:32

4

只需撥打strpos$_POST['Producer']作爲乾草堆和and作爲針。如果返回值爲false,則該字符串不包含and

現在你可以根據返回值創建你的輸出。

http://php.net/manual/en/function.strpos.php

+0

這個。將它構建到if語句中,如if(strpos($ _ POST ['Producer'],'和')!== false){$ verb ='is'} else {$ verb ='is'}' – 2012-07-20 16:38:48

0

我沒有測試過這個,但是沿着這條線應該有效。

$string = $_POST['Producer']; 

//This is the case if the user used and. 
$start = strstr($string, 'and'); 
if($start != null) 
{ 
    $newString = substr($string, 0, $start) . "are" . substr($string, $start+3, strlen($string)) 
} 
2

下面的代碼應該工作(未測試)。

if(!empty($_POST['Producer'])) { 
    $producer = $_POST["Producer"]; // CONSIDER SANITIZING 
    $pos = stripos($_POST['Producer'], ' and '); 
    list($verb, $pl) = $pos ? array('are', 's') : array('is', ''); 
    $description .= " $producer $verb the producer$pl of the movie"; 
} 

如前所述,你也應該考慮消毒的$ _ POST傳入值「生產者」],這取決於你打算如何使用格式化字符串。

相關問題