Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter some words

Tags:

arrays

php

I want to filter some reserved word on my title form.

$adtitle = sanitize($_POST['title']);
$ignore = array('sale','buy','rent');
if(in_array($adtitle, $ignore)) {
$_SESSION['ignore_error'] = '<strong>'.$adtitle.'</strong> cannot be use as your title';
header('Location:/submit/');
exit;
  • How to make something like this. If user type Car for sale the sale will detected as reserved keyword.
  • Now my current code only detect single keyword only.
like image 932
wow Avatar asked Sep 27 '26 06:09

wow


2 Answers

You're probably looking for a regular expression:

foreach($ignore as $keyword) {
  if(preg_match("/\b$keyword\b/i", $adtitle) {
    // Uhoh, the user used a bad word!!
  }
}

This will also prevent some false positives, such as 'torrent' not coming up as a reserved word because it contains 'rent'.

like image 160
Erik Avatar answered Sep 29 '26 20:09

Erik


You could also try something like this:

$ignore = array('sale','rent','buy');
$invalid = array_intersect($ignore, preg_split('{\W+}', $adtitle));

Then $invalid will contain a list of all the reserved words used in the title. This could be useful if you wanted to explain why the title cannot be used.

EDIT:

$invalid = array_intersect($ignore, preg_split('{\W+}', strtolower($adtitle));

if you want case-insensitive matching.

like image 28
Duncan Avatar answered Sep 29 '26 18:09

Duncan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!