|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2009-12-09 23:39 UTC] mail at daniel-faber dot de
Description: ------------ Please add these two string functions for convenience: boolean str_startswith($string, $prefix) // true if $string starts with $prefix, false otherwise boolean str_endswith($string, $suffix) // true if $string ends with $suffix, false otherwise Of course one can easily write these functions in PHP, but having them in the PHP core would be nice. You find them in other languages too: Java: string.startsWith(prefix) and string.endsWith(suffix) Python: string.startswith(prefix) and string.endswith(suffix) PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sat Oct 25 04:00:01 2025 UTC |
rasmus, this is right in nearly all cases, but here are some corner cases where your code fails: startswith('', '0') should be false, but your code gives true reason: substr('', 0, 1) is false false == '0' is true if you try to fix this by replacing == with ===, another corner case will fail: startswith('', '') should be true, but will be false reason: substr('', 0, 0) is false false === '' is false this seems to work in all cases: function str_startswith($string, $prefix) { if (strlen($string) < strlen($prefix)) return false; return substr($string, 0, strlen($prefix)) == $prefix; } similar for endswith: endswith('', '0') should be false, but is true endswith('test', '') should be true, but is false this seems to work in all cases: function str_endswith($string, $suffix) { $suffixLength = strlen($suffix); if ($suffixLength == 0) return true; if (strlen($string) < $suffixLength) return false; return substr($string, -$suffixLength) == $suffix; }