-3

I want to find 4 in a string. Just 4, not 44 or 14 or 4444 ...

I cannot use strpos because it returns 0 when 4 is found but also when 44 is found or when 444444 is found.

What function should I use?

Thanks

Miguel Mas
  • 547
  • 2
  • 6
  • 23
  • It returns zero because it found `4` in column `0` – RiggsFolly Oct 17 '16 at 11:05
  • @FrayneKonok I am not the one doing the guessing, you are – RiggsFolly Oct 17 '16 at 11:28
  • Welcome to SO. Please have a look at [the tour](http://stackoverflow.com/tour). You may also want to check [What topics can I ask about](http://stackoverflow.com/help/on-topic), and [How to ask a good question](http://stackoverflow.com/help/how-to-ask), and [The perfect question](http://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/), and how to create a [Minimal, Complete and Verifiable example](http://stackoverflow.com/help/mcve). Post the code you have tried and the errors you have received. Be as specific as possible as it will lead to better answers. – José Luis Oct 17 '16 at 12:25

2 Answers2

1

Try this, use preg_match_all

$str = 'Just 44 4 test 444';
preg_match_all('!\d+!', $str, $matches);
 // print_r($matches);


if (in_array("4", $matches[0])){
    echo "Match found";
  }
else
{
  echo "Match not found";
}

DEMO

Dave
  • 3,073
  • 7
  • 20
  • 33
0

Use preg_match() with negative lookbehind and negative lookahead:

preg_match('/((?<!4)4(?!4))/', $string, $m);
if ($m && count($m) == 2) {
  // matched "only one 4"
}
Ruslan Osmanov
  • 20,486
  • 7
  • 46
  • 60