Req #62573 [Wfx]: New String operators
Edit report at https://bugs.php.net/bug.php?id=62573&edit=1
ID: 62573
User updated by: thbley at gmail dot com
Reported by: thbley at gmail dot com
Summary: New String operators
Status: Wont fix
Type: Feature/Change Request
Package: *General Issues
PHP Version: Irrelevant
Block user comment: N
Private report: N
New Comment:
You can also skip == and write equals($str, $str2) like Java does.
Helper functions will be slower, need to be defined somewhere, included, namespaced, tested, etc.
Operators are good to read and make things easier. Perl does a lot of similar things with =~ and
people like it.
Previous Comments:
------------------------------------------------------------------------
[2012-07-23 13:30:43] nikic@php.net
It does not make any sense to introduce new operators just to save five characters. If you have to
do this really often and/or find strpos unreadable, you can simply define a few helper functions:
function contains($str1, $str2) {
return false !== strpos($str1, $str2);
}
function startsWith($str1, $str2) {
return 0 === strpos($str1, $str2);
}
function endsWith($str1, $str2) {
return 0 === substr_compare($str1, $str2, -strlen($str2), strlen($str2));
}
They have the additional advantage of being more clear than something like ~^.
------------------------------------------------------------------------
[2012-07-16 03:52:33] thbley at gmail dot com
Description:
------------
~ = matches substring (contains operator)
^~ = matches beginning of string (begins with operator)
~^ = matches ending of string (ends with operator)
$str = "abcdef";
old:
if (strpos($str, "bcd")!==false) {} // true
if (strpos($str, "abc")===0) {} // true
if (strpos($str, "def")===3) {} // true
new:
if ($str ~ "bcd") {} // true
if ($str ^~ "abc") {} // true
if ($str ~^ "def") {} // true
Test script:
---------------
$str = "abcdef";
assertTrue($str ~ "bcd");
assertTrue($str ^~ "abc");
assertTrue($str ~^ "def");
assertFalse($str ~ "aef");
assertFalse($str ^~ "bcd");
assertFalse($str ~^ "abc");
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=62573&edit=1
Thread (3 messages)