应拒绝的示例用户输入:
sale
rent
WTB
价格便宜的iphone 如何使我的代码拒绝上述输入?
$title = array('rent','buy','sale','sell','wanted','wtb','wts');
$user_title = stripslashes($_POST['title']);
if (in_array($user_title, $title)) {
$error = '<p class="error">Do not include ' . $user_title . ' on your title</p>';
}
答案 0 :(得分:4)
如果您希望被拒绝的单词是完整的单词而不仅仅是另一个单词的一部分而被视为被拒绝,则可以使用带有单词边界的基于正则表达式的解决方案:
// array of denied words.
$deniedWords = array('rent','buy','sale','sell','wanted','wtb','wts');
// run preg_quote on each array element..as it may have a regex meta-char in it.
$deniedWords = array_map('preg_quote',$deniedWords);
// construct the pattern as /(\bbuy\b|\bsell\b...)/i
$pat = '/(\b'.implode('\b|\b',$deniedWords).'\b)/i';
// use preg-match_all to find all matches
if(preg_match_all($pat,$user_title,$matches)) {
// $matches[1] has all the found word(s), join them with comma and print.
$error = 'Do not include ' . implode(',',$matches[1]);
}
答案 1 :(得分:1)
您可以使用stripos()
:
$title = array('rent','buy','sale','sell','wanted','wtb','wts');
$user_title = stripslashes($_POST['title']);
foreach($title as $word)
{
if (stripos($user_title, $word) !== false)
{
$error = '<p class="error">Do not include ' . $word . ' on your title</p>';
break;
}
}
答案 2 :(得分:0)
您也可以使用正则表达式:
if (preg_match("/(rent|buy|sale|sell|wanted|wtb|wts)/is", $user_title)) {
$error = '<p class="error">Do not include ' . $user_title . ' on your title</p>';
}
答案 3 :(得分:0)
你可以利用explode()来分隔$ user_title中的单词并检查每一个单词以确保它在$ title中不存在。
$invalidWords = '';
$words = explode(' ', stripslashes($_POST['title']));
foreach($words as $word) {
if (in_array($word, $title)) {
$invalidWords .= ' ' . $word;
}
}
if (!empty($invalidWords)) {
echo '<p class="error">Do not include the following words in your title: ' . $invalidWords . '</p>';
}
RegEx可能是最好的,但是我无法轻易找出所需的表达式,以便能够将列表中的所有无效单词输出给用户。