Reputation: 485
I want to know if how can I check I string (specifically an ip address) if that ip address has the string of x
For example
$ip = "66.124.61.23" // ip of the current user
$x = "66.124" // this is the string what I want to check in my $ip.
So how can I check $ip if it has the string of $x?
Please do leave a comment if you are having a hard time understanding this situation.
Thank you.
Upvotes: 2
Views: 30088
Reputation: 59709
You can also use strpos()
, and if you're specifically looking for the beginning of the string (as in your example):
if (strpos($ip, $x) === 0)
Or, if you just want to see if it is in the string (and don't care about where in the string it is:
if (strpos($ip, $x) !== false)
Or, if you want to compare the beginning n characters, use strncmp()
if (strncmp($ip, $x, strlen($x)) === 0) {
// $ip's beginning characters match $x
}
Upvotes: 5
Reputation: 31647
$email = '[email protected]';
$domain = strstr($email, '@');
echo $domain; // prints @example.com
Based on $domain, we can determine whether string is found or not (if domain is null, string not found)
This function is case-sensitive. For case-insensitive searches, use stristr().
You could also use strpos().
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);
// Note our use of ===. Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
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";
}
Also read SO earlier post, How can I check if a word is contained in another string using PHP?
Upvotes: 3
Reputation: 219914
Use strstr()
if (strstr($ip, $x))
{
//found it
}
See also:
stristr()
for a case insenstive version of this function.strpos()
Find the first occurrence of a stringstripos()
Find the position of the first occurrence of a case-insensitive substring in a stringUpvotes: 6
Reputation: 39522
Use strpos().
if(strpos($ip, $x) !== false){
//dostuff
}
Note the use of double equals to avoid type conversion. strpos
can return 0
(and will, in your example) which would evaluate to false with single equals.
Upvotes: 2