开发者

php version of pythons if in

开发者 https://www.devze.com 2023-01-28 06:54 出处:网络
Python has the great: if sub-string in string, like this: if \"fox\" in \"The quick brown fox jumps over the lazy dog\":

Python has the great: if sub-string in string, like this:

if "fox" in "The quick brown fox jumps over the lazy dog":
   print True

Does does PHP have someth开发者_运维问答ing equivalent to this?


Yes, see stripos and strpos

if(stripos("The quick brown fox jumps over the lazy dog","fox")!==false)
   { echo 'True'; }

stripos and strpos return the position at which the match started, so you need to use strict comparison (=== or !==) to avoid a false negative when the needle is at pos. 0 in the haystack.

You may prefer stristr, which just returns the matched string or boolean false.

in_array works about the same as in does in Python for lists and dictionaries, if you are also thinking beyond strings.


strpos


There's three that I can think of: substr, strpos, and strstr. Each of those are case sensitive, and there are also case insensitive versions of those functions as well. PHP has a ridiculous number of string handling commands, so really just peruse the string section of the manual until you see the one you want.


There's a few ways. One is:

if(stristr('fox','The quick brown fox jumps over the lazy dog') !== FALSE){
...code
}

http://php.net/manual/en/function.stristr.php

stripos and others may be more efficient. See PHP String Functions

0

精彩评论

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