Native PHP functions that allow double-dot range syntax
Asked Answered
E

1

3

Some native PHP string functions have a parameter which is a string of one or more unordered characters (also referred to as a "character mask"). In some cases, character ranges can be expressed using double-dot syntax.

For example: echo trim('foo24', '0..9'); prints foo because 2 and 4 fall within the 0 through 9 range.

What are the other native PHP string functions with the same feature?

Electrolyze answered 5/7, 2022 at 6:56 Comment(0)
E
8

Native PHP string functions that respect double-dot range expressions:

  • addcslashes() (Demo)

     echo addcslashes('adobe', 'a..e');
     // \a\do\b\e
    
  • chop() -- alias of rtrim() (Demo)

     echo chop('adobe', 'a..e');
     // ado
    
  • ltrim() (Demo)

     echo ltrim('adobe', 'a..e');
     // obe
    
  • rtrim() (Demo)

     echo rtrim('adobe', 'a..e');
     // ado
    
  • str_word_count() (Demo)

     var_export(
         str_word_count('do not break|on|pipe', 1, '{..}')
     );
     // ['do', 'not', 'break|on|pipe']
    
  • trim() (Demo)

     echo trim('adobe', 'a..e');
     // o
    
  • ucwords() (Demo)

     echo ucwords('backdoorman', 'a..e');
     // BaCkdOormaN
    

Here are some native functions where ranged expressions are not expanded, but might be reasonable candidates for the feature:

  • strcspn() (Demo) (expansion would be reasonable)

     echo strcspn('cdplayer', 'b..e');
     // 6
     // 0 if range enabled
    
  • strpbrk() (Demo) (expansion would be reasonable)

     echo strpbrk('stackoverflow', 'b..f');
     // flow
     // ckoverflow if range enabled
    
  • strspn() (Demo) (expansion would be reasonable)

     echo strspn('adobe', 'a..e');
     // 1
     // 2 if range enabled
    
  • strtok() (Demo) (expansion would be reasonable)

     echo strtok('toddler', 'a..e');
     // toddl
     // to if range enabled
    
  • strtr() (Demo) (out of topic scope because not technically a character mask -- character order matters)

     echo strtr('adobe', 'a..e', 'A..E');
     // AdobE
     // ADoBE if range enabled
    

Due to technical challenges of supporting .. syntax with multibyte characters, the following native functions will not allow ..
Ref: https://wiki.php.net/rfc/mb_trim

  • mb_ltrim()
  • mb_rtrim()
  • mb_trim()
Electrolyze answered 5/7, 2022 at 6:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.