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
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
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

Pull Requests

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-2024 The PHP Group
All rights reserved.
Last updated: Sat Nov 23 10:01:28 2024 UTC