2012-07-20 68 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传入值“生产者”],这取决于你打算如何使用格式化字符串。

相关问题