classic ASP instr for PHP


/ Published in: PHP
Save to your folder(s)

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)


Copy this code and paste it in your HTML
  1. function instr($haystack, $needle, $offset=0)
  2. {
  3. $result = stripos($haystack, $needle, $offset);
  4.  
  5. if (is_numeric($result))
  6. {
  7. $result++;
  8. }
  9. else
  10. {
  11. $result = 0;
  12. }
  13.  
  14. return $result;
  15. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.