Check if word exist in a string

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
winsonlee
Forum Commoner
Posts: 76
Joined: Thu Dec 11, 2003 8:49 pm

Check if word exist in a string

Post by winsonlee »

hey ....
just wondering how can i check that the information in $data is not found in $body before i attach the $data towards the $body ??
for example
$data = "cat";
$body = "i want a cat";

if cat found in $body then dont append data
else if cat not found in $body then append data

Code: Select all

$fh = fopen($myFile, 'rw') or die("can't open file");
$body = fread($fh, filesize($myFile));
$body = $body.$date;
fwrite($fh, $body);
fclose($fh);
User avatar
nielsene
DevNet Resident
Posts: 1834
Joined: Fri Aug 16, 2002 8:57 am
Location: Watertown, MA

Post by nielsene »

I'd probably use strpos()

Code: Select all

if (strpos($body,$data)===FALSE) {
  $body.=$data;
  fwrite($fh,$body);
}
fclose($fh);
Its important to use the triple equals '===' here. If the $data was found at the very beginning of $body, strpos would return '0' as that's where $data started, which would == FALSE, but not === false.
Post Reply