Test if a string contains a word in PHP?

痞子三分冷 提交于 2019-12-03 10:45:51

问题


In SQL we have NOT LIKE %string%

i need to do this in PHP.

if ($string NOT LIKE %word%) { do something }

i think that can be done with strpos()

but couldnt figure out how..

i need exactly that comparission sentence in valid PHP.

if ($string NOT LIKE %word%) { do something }

Thanks


回答1:


if (strpos($string, $word) === FALSE) {
   ... not found ...
}

Note that strpos() is case sensitive, if you want a case-insensitive search, use stripos() instead.

Also note the ===, forcing a strict equality test. strpos CAN return a valid 0 if the 'needle' string is at the start of the 'haystack'. By forcing a check for an actual boolean false (aka 0), you eliminate that false positive.




回答2:


Use strpos. If the string is not found it returns false, otherwise something that is not false. Be sure to use a type-safe comparison (===) as 0 may be returned and it is a falsy value:

if (strpos($string, $substring) === false) {
    // substring is not found in string
}

if (strpos($string, $substring2) !== false) {
    // substring2 is found in string
}



回答3:


<?php
//  Use this function and Pass Mixed string and what you want to search in mixed string.
//  For Example :
    $mixedStr = "hello world. This is john duvey";
    $searchStr= "john";

    if(strpos($mixedStr,$searchStr)) {
      echo "Your string here";
    }else {
      echo "String not here";
    }



回答4:


use 

if(stripos($str,'job')){
   // do your work
}


来源:https://stackoverflow.com/questions/9119101/test-if-a-string-contains-a-word-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!