note 41762 added to function.strpos
| From: | bishop at rn2 dot php dot net | Date: | Wed, 21 Apr 2004 19:38:36 +0000 |
| Subject: | note 41762 added to function.strpos | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-68475@lists.php.net to get a copy of this message | ||
Code like this:
<?php
if (strpos('this is a test', 'is') !== false) {
echo "found it";
}
?>
gets repetitive, is not very self-explanatory, and most people handle it incorrectly anyway. Make
your life easier:
<?php
function str_contains($haystack, $needle, $ignoreCase = false) {
if ($ignoreCase) {
$haystack = strtolower($haystack);
$needle = strtolower($needle);
}
$needlePos = strpos($haystack, $needle);
return ($needlePos === false ? false : ($needlePos+1));
}
?>
Then, you may do:
<?php
// simplest use
if (str_contains('this is a test', 'is')) {
echo "Found it";
}
// when you need the position, as well whether it's present
$needlePos = str_contains('this is a test', 'is');
if ($needlePos) {
echo 'Found it at position ' . ($needlePos-1);
}
// you may also ignore case
$needlePos = str_contains('this is a test', 'IS', true);
if ($needlePos) {
echo 'Found it at position ' . ($needlePos-1);
}
?>
----
Manual Page -- http://www.php.net/manual/en/function.strpos.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+41762
Delete -- http://master.php.net/manage/user-notes.php?action=delete+41762&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+41762&report=yes
Search -- http://master.php.net/manage/user-notes.php