-3

Possible Duplicate:
How can I check if a word is contained in another string using PHP?

I wish to have some PHP code to check if a certain number appears in a string of numbers, so for example how do I check if the number 7 appears in the number 3275?

I have tried strcmp but I can't work this one out :(

Community
  • 1
  • 1
James Clifton
  • 185
  • 3
  • 14

6 Answers6

3

Try this code:

$pos = strrpos($mystring, "7");
if ($pos === false) { // note: three equal signs
    // not found...
}
else{
    //string found
}
Alessandro Minoccheri
  • 35,521
  • 22
  • 122
  • 171
  • Note that 'strrpos' find the last occurance, as opposed to 'strpos' which finds the first appearance. Either function will for this use case. – Omn May 25 '13 at 17:22
2

Have a look at strpos; you can use it to find where a substring occurs in a string (and, by extension, whether it occurs). See the first example for how to do the check correctly.

Will Vousden
  • 32,488
  • 9
  • 84
  • 95
2

strpos() is your friend, php is not strongly typed, so you can consider numbers as strings.

$mystring = 3232327;
$findme   = 7;
$pos = strpos($mystring, $findme);

if ($pos === false) {
    echo "The number '$findme' was not found in the number '$mystring'";
} else {
    echo "The number '$findme' was found in the number '$mystring'";
    echo " and exists at position $pos";
}
napolux
  • 15,574
  • 9
  • 51
  • 70
1

http://us3.php.net/strpos

int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

Find the numeric position of the first occurrence of needle in the haystack string.

make sure you use " !== false" when comparing the return value to see if it exists (otherwise 7325 would return position 0 and 0 == false) - === and !== are compare value AND type (boolean vs integer)

msEmmaMays
  • 1,073
  • 7
  • 7
0
if(stristr('3275', '7') !== false)
{
  // found
}
Sherlock
  • 7,525
  • 6
  • 38
  • 79
0

Try like this

$phno = 1234567890;
$collect = 4;
$position = strpos($phno, $collect);

if ($position)
    echo 'The number is found at the position'.$position;   
else
    echo 'Sorry the number is not found...!!!';
GautamD31
  • 28,552
  • 10
  • 64
  • 85