php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #62573 New String operators
Submitted: 2012-07-16 03:52 UTC Modified: 2012-07-23 13:57 UTC
From: thbley at gmail dot com Assigned:
Status: Wont fix Package: *General Issues
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: thbley at gmail dot com
New email:
PHP Version: OS:

 

 [2012-07-16 03:52 UTC] 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");



Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2012-07-23 13:30 UTC] 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-23 13:30 UTC] nikic@php.net
-Status: Open +Status: Wont fix
 [2012-07-23 13:57 UTC] thbley at gmail dot com
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.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sun Jun 02 08:01:31 2024 UTC