Jump to content

Strip common words


dreamwest

Recommended Posts

Arras are really simple once you get into them, and you cannot code without them :).

 

<?php

$disallowed = array(
   "at",
   "the",
   "a",
   "or",
   "and"
); // and about 1 hundred other words lol.

?>

 

then you may need a more advanced regex pattern, to use "preg_replace". Ask in the regex forum for help with that, something like: "/\A[ ]{0,1}".$current_word."[ ]{0,1}$/i" - this should work, but there might be more effective methods.

 

My Example:

 

<?php

$disallowed = array(
   "at",
   "the",
   "a",
   "or",
   "and"
); // and about 1 hundred other words lol.

//set string
$string = $_POST['search']; // $_POST from form data.

//loop
foreach($disallowed As $current_word){
   $string = preg_replace("/\A[ ]{0,1}".$current_word."[ ]{0,1}$/i"," ",$string);
}

echo($string);

?>

 

The aim is to not leave half a word, eg:

if ou searched for 'sweat', and ou filtered 'at', ou would be left with 'swe'. So you need a regex pattern that could handle that. or use a different method - like splitting the string into an array itself and remove specific values.

 

- uniflare

Link to comment
https://forums.phpfreaks.com/topic/144893-strip-common-words/#findComment-760361
Share on other sites

None of these work...

 

My string is  "She walks down the street at night"

 

and i used all the examples but the string stays the same

 

$disallowed = array(
   "at",
   "the",
   "a",
   "or",
    "on",
     "On",
   "and"
); // and about 1 hundred other words lol.

//set string
$string =  "She walks down the street at night";
//loop
foreach($disallowed As $current_word){
   $string = preg_replace("/\A[ ]{0,1}".$current_word."[ ]{0,1}$/i"," ",$string);
}

echo($string);

Link to comment
https://forums.phpfreaks.com/topic/144893-strip-common-words/#findComment-760374
Share on other sites

None of these work...

 

My string is  "She walks down the street at night"

 

and i used all the examples but the string stays the same

 

$disallowed = array(
   "at",
   "the",
   "a",
   "or",
    "on",
     "On",
   "and"
); // and about 1 hundred other words lol.

//set string
$string =  "She walks down the street at night";
//loop
foreach($disallowed As $current_word){
   $string = preg_replace("/\A[ ]{0,1}".$current_word."[ ]{0,1}$/i"," ",$string);
}

echo($string);

 

Use this

 

<?php
$wordlist = array("the", "at");

$string = "She walks down the street at night atleast";

foreach($wordlist as $word)
    $string = preg_replace("/\s". $word ."\s/", " ", $string);

print $string;
?>

Link to comment
https://forums.phpfreaks.com/topic/144893-strip-common-words/#findComment-760387
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.