Matu
Matu

Reputation: 17

Strip first word from a string

I basically have a script that lets users post comments but I have it setup so that at the begin of every comment the user put in the script puts in hate automactically which is how I want it to work, but sometimes the user put in hating themselves and it comes out with hating hating and then users comment. Anyone have any ideas on how I can get it to strip out hating or hates if it is the first word in the sentence inputted by the user? At the moment I have it set to remove hating but it removes it where ever it is used in the sentence which is not good at the moment. Here is some of the code that is being used.

if (strpos($content, 'hating') !== false) {
  $content = str_replace("hating", "", $content);
  }

  $query="INSERT INTO posts SET story='hating ".mysql_real_escape_string($content)."', time_added='".time()."', date_added='".date("Y-m-d")."', active='$active', pip='".$_SERVER['REMOTE_ADDR']."'"; 
  $result=$conn->execute($query);
  $pid = mysql_insert_id();

SET story='hating " is where I have set it to put in the word hating and include it in the database when submitted.

Upvotes: 1

Views: 862

Answers (2)

Liam
Liam

Reputation: 1768

Here is some code that will make sure that you're making the safest inquiry into this:

if(substr(rtrim(strtolower($content)), 0,5)=="hating")
{
   $content = rtrim(substr($content,6,strlen($content)));
}

This way you can get the 'hating' at the beginning as well as take into account any extra spaces that could also be input mistakenly by the user. You should also normalize the text to lowercase just in case the user enters a capital letter within the input field when typing 'hating' or 'Hating'

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324600

Try:

$content = preg_replace("(^hating )","",$content);

Upvotes: 2

Related Questions