2

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.

Juvar Abrera
  • 465
  • 3
  • 10
  • 21

4 Answers4

6

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 string
  • stripos() Find the position of the first occurrence of a case-insensitive substring in a string
John Conde
  • 217,595
  • 99
  • 455
  • 496
5

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
}
Default
  • 684
  • 9
  • 19
nickb
  • 59,313
  • 13
  • 108
  • 143
3

Use strstr()

$email  = 'name@example.com';
$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?

Community
  • 1
  • 1
Fahim Parkar
  • 30,974
  • 45
  • 160
  • 276
2

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.

SomeKittens
  • 38,868
  • 19
  • 114
  • 143