is there an "if in" operator in PHP?
i was looking to something that checks whether a string exists inside another, as in p开发者_高级运维ython:
print "a" in "aloha"
wold return 1
strpos()
$pos = strpos("aloha", "a");
EDIT
You can verify the existence of string by putting IF
like this:-
if (strpos("aloha", "a") !== false) {
echo "The string was found";
} else {
echo "The string was not found";
}
strpos("aloha", "a") !== false
Returns true is the letter a is in the word aloha.
Note: Its important to use !==
and not !=
as in PHP 0 == false
.
try
$mystring = 'aloha';
$findme = 'a';
$pos = strpos($mystring, $findme);
echo $pos // return 0
if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'";
} else {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
}
You can use the srtpos()
function to check if the position of a string inside another is not false -- i.e. if the string contains the other :
if (strpos("aloha", "a") !== false) {
// a is contained in aloha
}
The first parameter being the haystack -- the string that could contain what you are searching ; and the second parameter being the needle -- the string you are searching.
As noted in the manual (quoting) :
This function may return Boolean
FALSE
, but may also return a non-Boolean value which evaluates toFALSE
, such as0
or""
.
Please read the section on Booleans for more information.
Use the===
operator for testing the return value of this function.
If you want the search to be case-insentive, you'll use the stripos()
function, btw.
精彩评论