我有一个典型的问题,我不确定这是否可能。我有一个表格,里面有一个字段,即Producer。如果用户在字段中使用单词和,然后在结果中插入单词;如果用户在域中不使用单词和,则在结果中添加单词1。让我举个例子来解释你。
示例(字段中有单词和)然后生成以下结果:
ABC和DEF是电影的制片人。
示例(单词和不在字段中)然后生成以下结果:
XYZ是这部电影的制片人。
我有以下代码:
if(!empty($_POST['Producer'])) {
$description .= ' ' . $_POST["Producer"] . ' is/are the producer(s) of the movie';
}
如果有人有这个想法,请告诉我。
简单地调用strpos
,将$_POST['Producer']
作为草垛,将and
作为针。如果返回值为false,则该字符串不包含and
。
现在,您可以根据返回值创建输出。
http://php.net/manual/en/function.strpos.php
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'
(带空格),因为有些名称包含单词"are",所以即使只有一个名称,它也会返回true。
下面的代码应该可以工作(未测试)。
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["Producer"]的传入值,具体取决于您打算如何使用格式化字符串。
我还没有测试过这一点,但类似的东西应该可以工作。
$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))
}