php.net |  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
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: stanislav dot eckert at vizson dot de
New email:
PHP Version: OS:

 

 [2017-04-15 17:41 UTC] stanislav dot eckert at vizson dot de
Description:
------------
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()).


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2017-04-16 06:34 UTC] requinix@php.net
-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] requinix@php.net
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-2019 The PHP Group
All rights reserved.
Last updated: Fri Aug 23 11:01:26 2019 UTC