3

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 something equivalent to this?

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the note about the strict comparison
2

strpos

Comments

1

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.

Comments

1

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

1 Comment

its ===|!== for type comparison its ==|!= for value comparison, and = to assign

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.