Req #74449 [Opn->Dup]: Check string begins with function: str_begins()
Edit report at https://bugs.php.net/bug.php?id=74449&edit=1
ID: 74449
Updated by: requinix@php.net
Reported by: stanislav dot eckert at vizson dot de
Summary: Check string begins with function: str_begins()
-Status: Open
+Status: Duplicate
Type: Feature/Change Request
Package: Strings related
PHP Version: Irrelevant
Block user comment: N
Private report: N
New Comment:
See https://wiki.php.net/rfc/add_str_begin_and_end_functions
and the commentary in the PR https://github.com/php/php-src/pull/2049
By the way, have you seen http://php.net/manual/en/function.strncmp.php
?
Previous Comments:
------------------------------------------------------------------------
[2017-04-15 17:41:38] 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()).
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=74449&edit=1
Thread (4 messages)