Re: Check if string contains matched words.



Eureka22 wrote:
Hi,
If the file contained each word on a new line, you could do something like this (written, but not tested).

<?php
$match = false;
$string_to_match = "This apple is yellow";
$words = file("filter.txt");

// loop through each word in the file
foreach($words as $word)
{
if(strpos($string_to_match, $word) !== false)
{
$match = true;
}
}

// Return the result
if($match == true)
{
echo("Match found");
}
else
{
echo("No match found");
}
?>

$match contains whether a match has been found or not

$string_to_match is the string you want to search

$words is an array of each line in the the file filter.txt

strpos() is a function for search for the position of a string within a string

Hope this helps, Cheers

Leigh Finch
http://www.phpmaniac.net


Thanks for your response. The script like this I.m looking for.
In the file each word is on a new line.
I tested the script, but in all cases I get "No match found"
Hi,
My bad, forgot to trim line feeds off the end of the words to match. Try this.

<?php
$match = false;
$string_to_match = "This apple is yellow";
$words = file("filter.txt");

// loop through each word in the file
foreach($words as $word)
{
if(strpos($string_to_match, rtrim($word)) !== false)
{
$match = true;
}
}

// Return the result
if($match == true)
{
echo("Match found");
}
else
{
echo("No match found");
}
?>

Hope this helps, Cheers

Leigh Finch
http://www.phpmaniac.net
.



Relevant Pages

  • RE: [PHP] Script feedback: insert string into another string
    ... Subject: [PHP] Script feedback: insert string into another string ...
    (php.general)
  • Re: parameter passing from asp to php
    ... > I've got a script using com objects that will work in asp but not work ... I want this sting to be passed to an php script without ... string, for example? ...
    (comp.lang.php)
  • Re: Securing an Email script
    ... Bill H wrote: ... The script looks like: ... /* PHP form validation: the script checks that the Email field contains a valid email address ... error string otherwise. ...
    (comp.lang.php)
  • Re: Any way PHP can directly initiate/execute a HTTP connection+download?
    ... can't find any pure-PHP tool for, given a URL (with query string), ... Unix/Linux program from inside PHP. ... script running Common Lisp on my Unix shell account, ... string specifying what exactly the CGI/CL script is supposed to do, ...
    (comp.lang.php)
  • Re: [PHP] PHP console script vs C/C++/C#
    ... My script is taking a longer time to execute than I want. ... I prefer to write in PHP because that is what I know best. ... This is why I am thinking about rewriting my whole script in a C language. ... Perhaps there are different methods I could be using to speed up execution. ...
    (php.general)