search for a word inside a string.

[php]<?php
if(strstr($_POST[‘textbox1’],‘hit’))
{
function1();
}
elseif(strstr($_POST[‘textbox1’],‘your’))
{
function2();
}
else
{
echo “Error in log.”;
}[/php]

If i type in “Your friend is a hitman”. I want function2 to be called, not function1. Is there anyway i can do that?
Also is there any php function to search for a separate word(not a phrase) inside a string?

would it be safe to assume you are trying to search for whole words rather than a simple string search. If so PHP’s built in standard string functions won’t do the job. You will probably wish to look into regular expressions.

the preg_match function (manual entry: http://php.net/manual/en/function.preg-match.php) will suffice. The pattern you will want to use will be composed of the search string (in the first case it would be “hit”) surrounded by the word boundries metacharacter: \b (link: http://www.regular-expressions.info/wordboundaries.html)

so your first if statement would become

[php]
if (preg_match(’/\bhit\b/’, $_POST)){
function1();
}
[/php]

your second if statement would be changed in a similar fashion. My knowledge of regex isn’t incredibly strong, so that pattern may be a little off, but the concept is correct.

Hope this helps

An alternate method, provided your string isn’t too long is this:

$sentence = explode(' ',trim($_POST['textbox1'])); if(array_search('hit',$sentence) !== false) { function1(); } else if(array_search('your',$sentence) !== false) { function2(); }

The regular expression method should also work for you, but if you don’t know about them and want to change what you are matching, you may discover issues in regards to correctly escaping characters etc.

Sponsor our Newsletter | Privacy Policy | Terms of Service