Page 1 of 1

Check if word exist in a string

Posted: Thu Sep 01, 2005 9:27 am
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);

Posted: Thu Sep 01, 2005 9:31 am
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.