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.

3

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

1 Comment

strpos would be more appropriate here.
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
}

Comments

3

Use strstr()

$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?

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.