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
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: 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

Pull Requests

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-2025 The PHP Group
All rights reserved.
Last updated: Thu Jul 17 13:01:33 2025 UTC