|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #74449 Check string begins with function: str_begins()
Submitted: 2017-04-15 17:41 UTC Modified: 2017-04-16 18:14 UTC
From: stanislav dot eckert at vizson dot de Assigned:
Status: Duplicate Package: Strings related
PHP Version: Irrelevant OS:
Private report: No CVE-ID: None
 [2017-04-15 17:41 UTC] stanislav dot eckert at vizson dot de
A quite often used code is to check if a string / binary string begins with a certain substring. Using substr() requires setting 2nd param always to 0 and 3rd param to length, which is the often set hardcoded or with strlen() / mb_strlen(). Example:

substr($str, 0, 7) == "http://"
// or
substr($str, 0, strlen("http://")) == "http://"

This can lead to errors, when user sets wrong length, mixes substr() & strlen() with their multibyte versions, etc. A shorter version could be done with strpos() and checking for position 0, but strpos() searches the entire string. RegEx has performance implications.

A simple function would result in a cleaner and a more robust and readable code. Example:

str_begins($str, $substr)  // => true / false

Its performance can also be optimized quite good, I think (compared to substr()).


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2017-04-16 06:34 UTC]
-Status: Open +Status: Duplicate
 [2017-04-16 10:36 UTC] stanislav dot eckert at vizson dot de
strncmp() is quite good too, but it still requires manually setting a length value and it does not seem to accept negative offsets (for str_end() like functionality). I understand, that this is not a truly mandatory function - it just would be nice to have it. Low priority. 

Your link references are perfect! I didn't see that, thank you. Should I close the report now or just leave it as is?
 [2017-04-16 18:14 UTC]
As is. Duplicate doesn't mean open or closed but that there is another bug/request already being used to track the issue.

For the sake of automatic linkage: request #50434
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Jul 25 04:01:28 2024 UTC