开发者

How to find some words contain in string?

开发者 https://www.devze.com 2023-03-03 16:17 出处:网络
I wish to do this in PHP find some words contain in a string if (strpos($str,array(\"select\",\"update\",\"insert into\",\"delete\") !== False){

I wish to do this in PHP find some words contain in a string

  if (strpos($str,array("select","update","insert into","delete") !== False){
    echo "string开发者_JAVA技巧 contain SQL statements";
  }

Anyone know how to do this?


If you mean that you want to detect if any of the word is contained in the string, you can do:

$sql_words = array(...);

if(count(array_intersect(explode(' ', strtolower($str)), $sql_words)) > 0) {

}

Although if a string contains select, it does not mean that it is a SQL query. But I guess that depends on the context.

Depending on the string you might also want to use str_word_count.


You can use strstr function as follows:

$string_to_be_searched_in = "SELECT * FROM MyTable";
$sqlWords = array("insert", "update", "delete" ...);

foreach($sqlWords as $word) {
    if(strstr($string_to_be_searched_in, $word) != FALSE) {
        echo "The given string is an SQL statement";
    }
}


The function you want to use is preg_match(). It uses regular expressions to match patterns to a string, and returns the number of times the pattern matched - if you pass through an array as a parameter, you can also use it to extract information form the string (in your example, you could pull what the query was).

You should read these pages on using regular expressions with PHP, and this page will allow you to test regular expressions.


try

 $string = "i m where ?";
 $searchfor = array("select","from","where","and","and",update,"set","insert","into","value");

foreach($searchfor as $v) {
  if(false !== strpos($string, $v) ) {
    //Found a word
    echo 'Found '.$v;
    break;
  }
}

Reference:

strpos

also study

case sensitive strstr and
case insensitive : stristr

0

精彩评论

暂无评论...
验证码 换一张
取 消