note 110859 added to function.substr-compare
| From: | jimmetry at gmail dot com | Date: | Sun, 16 Dec 2012 00:31:06 +0000 |
| Subject: | note 110859 added to function.substr-compare | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-192548@lists.php.net to get a copy of this message | ||
When you came to this page, you may have been looking for something a little simpler: A function
that can check if a small string exists within a larger string starting at a particular index. Using
substr_compare() for this can leave your code messy, because you need to check that your string is
long enough (to avoid the warning), manually specify the length of the short string, and like many
of the string functions, perform an integer comparison to answer a true/false question.
I put together a simple function to return true if $str exists within $mainStr. If $loc is
specified, the $str must begin at that index. If not, the entire $mainStr will be searched.
<?php
function contains_substr($mainStr, $str, $loc = false) {
if ($loc === false) return (strpos($mainStr, $str) !== false);
if (strlen($mainStr) < strlen($str)) return false;
if (($loc + strlen($str)) > strlen($mainStr)) return false;
return (strcmp(substr($mainStr, $loc, strlen($str)), $str) == 0);
}
?>
----
Server IP: 69.147.83.199
Probable Submitter: 115.64.209.221
----
Manual Page -- http://php.net/manual/en/function.substr-compare.php
Edit -- https://master.php.net/note/edit/110859
Del: integrated -- https://master.php.net/note/delete/110859/integrated
Del: useless -- https://master.php.net/note/delete/110859/useless
Del: bad code -- https://master.php.net/note/delete/110859/bad+code
Del: spam -- https://master.php.net/note/delete/110859/spam
Del: non-english -- https://master.php.net/note/delete/110859/non-english
Del: in docs -- https://master.php.net/note/delete/110859/in+docs
Del: other reasons-- https://master.php.net/note/delete/110859
Reject -- https://master.php.net/note/reject/110859
Search -- https://master.php.net/manage/user-notes.php