Posted By

seloh77 on 07/13/10


php ASP

Versions (?)

classic ASP instr for PHP

 / Published in: PHP

I used to program in classic ASP and would sometimes check if a certain word or letter would be in a string with instr.

if instr(haystack, needle)>0 then DO SOMETHING end if

If the needle starts on the first position of the haystack, instr returns 1. If the needle is not in the haystack, instr returns 0.

PHP has the strpos and stripos functions which return FALSE if the needle is not in the haystack and return 0 if the needle starts on the first position of the haystack. I wanted to be able to do a quick check on a string, without checking type so I created the instr function for PHP.

if (instr($haystack, $needle)>0) { DO SOMETHING }

(an offset can be given but is optional)

  1. function instr($haystack, $needle, $offset=0)
  2. {
  3. $result = stripos($haystack, $needle, $offset);
  5. if (is_numeric($result))
  6. {
  7. $result++;
  8. }
  9. else
  10. {
  11. $result = 0;
  12. }
  14. return $result;
  15. }

Report this snippet  


RSS Icon Subscribe to comments
Posted By: leond on July 14, 2010

I think you can use PHP function strstr or stristr (cap. insensitive)

Posted By: seloh77 on July 22, 2010

strstr or stristr both return a string if the needle is in the haystack else they return false I quickly want to see if a needle is in a haystack with: if (instr($haystack, $needle)>0) { DO SOMETHING }

You need to login to post a comment.