This topic describes the syntax, features, parameters, and return values of string functions. This topic also provides examples of these functions.

substr | concat | format | upper | lower | len | byte | match_re | capture_re | gsub_re | split | split_as_key | tohex | tobin | tostring | tochar | reverse | find | trim

substr

ItemDescription
Syntaxsubstr(s, i, j)
DescriptionExtracts a substring from a string.
Parameter
  • s: the string from which you want to extract a substring.
  • i: the position at which the extraction starts, counting from 1. A value of -1 specifies the rightmost character of the string. Data type: integer.
  • j: the position at which the extraction ends, counting from 1. A value of -1 specifies the rightmost character of the string. Data type: integer.
Return valueA substring s[i, j] that is extracted from the source string specified by s is returned.
ExampleYou can use the following methods to determine whether a file is an M3U8 file:
  • Method 1:
    if eq(substr($uri, -5, -1), '.m3u8') {
        say(concat($uri, ' is .m3u8'))
    }
  • Method 2:
    uri_len = len($uri)
    if eq(substr($uri, -5, uri_len), '.m3u8') {
        say(concat($uri, ' is .m3u8'))
    }

concat

ItemDescription
Syntaxconcat(s1, ...)
DescriptionConcatenates strings.
ParameterThe strings that you want to concatenate. You can specify one or more strings. Numeric values are supported.
Return valueA concatenated string.
ExampleYou can use the following methods to determine whether a file is an M3U8 file:
  • Method 1:
    if eq(substr($uri, -5, -1), '.m3u8') {
        say(concat($uri, ' is .m3u8'))
    }
  • Method 2:
    uri_len = len($uri)
    if eq(substr($uri, -5, uri_len), '.m3u8') {
        say(concat($uri, ' is .m3u8'))
    }

format

ItemDescription
Syntaxformat(fmt, ···)
DescriptionFormats the values of one or more parameters. The format string is the first parameter, which must specify a string. The format string follows the specification of the sprintf parameter used by functions in the ISO C programming language.
The syntax of a format string specified by fmt is %[parameter][flag][field width][precision]specifier.
%%: prints literal percentage signs (%). 
%c: converts integers into ASCII characters. 
%d: coverts integers into decimal numbers. 
%f: converts N-precision numbers into floating point numbers. 
%o: converts integers into octal numbers. 
%s: converts integers into strings. 
%x: converts integers into hexadecimal numbers in lowercase letters. 
%X: converts integers into hexadecimal numbers in uppercase letters. 
Parameter
  • fmt: the string type. This parameter specifies a format string.
  • The variable number of parameters: any type.
Return valueA string.
Example
say(concat('format:', format('%%%s$%.2s$%s$%c$%d$%2.2f$%.2o$%x$%X', 'format', 3.1415926, true, 95, 3.1415926, 3.1415926, 3.1415926, 10, 10)))
Output:
format:%format$3.$true$_$3$3.14$03$a$A

upper

ItemDescription
Syntaxupper(s)
DescriptionConverts a string to uppercase letters.
Parameters: the string that you want to convert.
Return valueThe string specified by the s parameter in uppercase letters.
Example
mystr = 'Hello, AScript'
say(upper(mystr))
say(lower(mystr))
Output:
HELLO, ASCRIPT
hello, ascript

lower

ItemDescription
Syntaxlower(s)
DescriptionConverts a string to lowercase letters.
Parameters: the string that you want to convert.
Return valueThe string specified by the s parameter in lowercase letters.
Example
mystr = 'Hello, AScript'
say(upper(mystr))
say(lower(mystr))
Output:
HELLO, ASCRIPT
hello, ascript

len

ItemDescription
Syntaxlen(s)
DescriptionQueries the length of a string.
Parameters: the string that you want to query.
Return valueThe length of the string specified by the s parameter. Data type: integer.
ExampleYou can use the following methods to determine whether a file is an M3U8 file:
  • Method 1:
    if eq(substr($uri, -5, -1), '.m3u8') {
        say(concat($uri, ' is .m3u8'))
    }
  • Method 2:
    uri_len = len($uri)
    if eq(substr($uri, -5, uri_len), '.m3u8') {
        say(concat($uri, ' is .m3u8'))
    }

byte

ItemDescription
Syntaxbyte(c)
DescriptionQueries the ASCII value of a character.
Parameterc: the character whose ASCII value you want to query. You can specify only one character.
Return valueThe ASCII value of the specified character. Data type: numeric.
Example
say(byte('a'))
say(byte('A'))
Output:
97
65

match_re

ItemDescription
Syntaxmatch_re(s, p [, o])
DescriptionUses the Perl Compatible Regular Expressions (PCRE) engine for regular expression matching. For more information, see PCRE syntax.
Parameter
  • s: the string that you want to match. Data type: string.
  • p: the regular expression for matching. Data type: string.
  • o: the regular expression engine. Data type: string. This parameter is optional.
Return valueIf the string matches the regular expression, true is returned. Otherwise, false is returned.
Example
url = concat('http://', $host, $uri)
m1 = match_re(url, 'http://.*\.dslex\.com/.*')
m2 = match_re(url, '^http://.*\.alibaba\.com\.cn/.*\.d\\.html(\?.*)?$')
m3 = match_re(url, '^http://.*.test.dslex.com/.*\.d\.html(\?.*)?$')
m4 = match_re(url, '^http://.*\.alibaba\.com\.cn/zt_d/')
m5 = match_re(url, '^http://tech.alibaba.com.cn/zt_d/we2015/?$')
m6 = match_re($args, 'from=wap1$')
m7 = match_re($args, 'from=comos1$')

if and(m1, or(m2, m3), not(m4), not(m5), or(not(m6), not(m7))) {
    add_rsp_header('USER-DEFINED-1', 'hit1')
    add_rsp_header('USER-DEFINED-2', 'hit2')
}                                                                                                                                                        

capture_re

ItemDescription
Syntaxcapture_re(s, p [,init])
DescriptionCaptures the matches of a string and returns the matching substrings. For more information about PCRE, see PCRE syntax.
Parameter
  • s: the string that you want to match. Data type: string.
  • p: the regular expression for matching. Data type: string.
  • init: the position to start matching, counting from 1. Data type: integer.
Return valueIf the string matches the regular expression, the matching substrings in the dictionary type are returned. Otherwise, an empty dictionary is returned.
Example
pcs = capture_re($request_uri,'^/([^/]+)/([^/]+)([^?]+)\?(.*)')
sec1 = get(pcs, 1)
sec2 = get(pcs, 2)
sec3 = get(pcs, 3)
if or(not(sec1), not(sec2), not(sec3)) {
   add_rsp_header_imm('X-TENGINE-ERROR', 'auth failed - missing necessary uri set')
   exit(403)
}
digest = md5(concat(sec1, sec3))
if ne(digest, sec2) {
    add_rsp_header_imm('X-TENGINE-ERROR', 'auth failed - invalid digest')
    exit(403)
}                                                                                                                                              

gsub_re

ItemDescription
Syntaxgsub_re(subject, regex, replace [,option])
DescriptionReplaces all matches of a string and returns the string after the replacement. For more information about PCRE, see PCRE syntax.
Parameter
  • subject: the string that you want to match. Data type: string.
  • regex: the regular expression. Data type: string.
  • replace: the string for replacement. Data type: string.
    You can specify the replace parameter by using the matching substrings.
    • $0: specifies all substrings that match regex.
    • $N: specifies the substring that matches the Nth parenthesized subexpression () of regex.
  • option: the regular expression engine. Data type: string. This parameter is optional.
Return valueThe function replaces all substrings that match the specified regex parameter in the specified subject parameter with those specified by the replace parameter and returns the string after the replacement.
Example
subject = 'Hello, Es'
regex = '([a-zA-Z])[a-z]+'
replace = '[$0,$1]'
add_rsp_header('X-DEBUG-GSUB-RE', gsub_re(subject, regex, replace))                                                                                                                         
Output:
X-DEBUG-GSUB-RE: [Hello,H], [Es,E] 

split

ItemDescription
Syntaxsplit(s [,sep])
DescriptionSplits a string into an array of substrings and returns the array.
Parameter
  • s: the string that you want to split. Data type: string.
  • sep: the separator that is used to split the string. Data type: string.
Return valueAn array of key-value pairs in the dictionary type. The value of the key parameter is a number that starts from 1, for example, [1]=xx, [2]=yy. If sep is left empty, the string is split by whitespace characters. Whitespace characters include space characters and tab characters (\t).
Example
if $arg_from {
    t = split($arg_from, ',')
    if get(t, 1) {
        say(concat('[1]=', get(t, 1)))
    }
    if get(t, 2) {
        say(concat('[2]=', get(t, 1)))
    }
}                                                                                                                               
Request:
?from=xx1,xx2,xx3
Response:
[1]=xx1
[2]=xx1 

split_as_key

ItemDescription
Syntaxsplit_as_key(s [,sep])
DescriptionSplits a string into an array of substrings and returns the array.
Parameter
  • s: the string that you want to split. Data type: string.
  • sep: the separator that is used to split the string. Data type: string.
Return valueResponse parameters are returned in the same way as the split() function. However, the key parameter is named after each split element: Element 1 -> Element 2.
Example
def echo_each(k, v, u) {
    s = concat(k, '=', v, ' u=', get(u, 1))
    say(s)
}
if $arg_from {
    t = split_as_key($arg_from, ',')
    foreach(t, echo_each, ['hi,ascript'])
}                                                                                                                             
Request:
?from=xx1,xx2,xx3
Response:
xx2=xx2 u=hi,ascript
xx1=xx1 u=hi,ascript
xx3=xx3 u=hi,ascript

tohex

ItemDescription
Syntaxtohex(s)
DescriptionConverts a string to a hexadecimal string.
Parameters: the string that you want to convert.
Return valueA hexadecimal string that is converted from the string specified by the s parameter.
Example
digest = sha1('xxxx')
add_rsp_header('X-AScript-TOHEX', tohex(digest))                                                                                                                            
Output:
X-AScript-TOHEX:4ad583af22c2e7d40c1c916b2920299155a46464 

tobin

ItemDescription
Syntaxtobin(str)
DescriptionConverts a hexadecimal string to an ASCII string.
Parameterstr: the hexadecimal string that you want to convert. It is not case-sensitive.
Return valueA string.
Example
say(concat('tobin:', tobin('2F2F')))                                                                                                                              
Output:
tobin://

tostring

ItemDescription
Syntaxtostring(a)
DescriptionConverts data of any type to a string.
Parametera: the data that you want to convert. Data type: any type.
Return valueA string that is converted from the value specified by the a parameter.
Example
s = tostring(123)
add_rsp_header('X-DSL-TOSTRING', s)                                                                                                                      
Output:
X-DSL-TOSTRING: 123

tochar

ItemDescription
Syntaxtochar(n1, n2, ...)
Description
  • Converts one or more internal integers to a string. For example, 48 corresponds to the character "0".
  • The length of the returned string is based on the number of specified parameters.
ParameternX: the integers that you want to convert. You can specify one or more integers.
Return valueA string that is converted from integers.
Example
add_rsp_header('X-DSL-TOCHAR', tochar(97))
add_rsp_header('X-DSL-TOCHAR', tochar(97, 98), true)
//Output: A response header is added.
//X-DSL-TOCHAR: a
//X-DSL-TOCHAR: ab

if $arg_filename {
    hn = 'Content-Disposition'
    add_rsp_header('Content-Disposition', concat('attachment;filename=', tochar(34), filename, tochar(34)))

}                                                                                                                                  
Output: A response header is added
Content-Disposition: attachment;filename="The value of the filename parameter" 

reverse

ItemDescription
Syntaxreverse(str)
DescriptionReverses a string.
Parameterstr: the string that you want to reverse.
Return valueA string reversed from the specified string. Data type: CHAR.
Example
say(reverse('hello'))
Output:
olleh

find

ItemDescription
Syntaxstring.find (s, substr, pos)
DescriptionSearches for a substring in a specified string.
Parameter
  • s: the string that you want to search.
  • substr: the substring for which you want to search.
  • pos: the position where the search starts. Data type: numeric. This parameter is optional. You can specify a negative integer. The default value is 1.
Return value
  • An array is returned if the specified substring is found.
    • Index 1 indicates the position where the search starts.
    • Index 2 indicates the position where the search ends.
  • An empty array is returned if the specified substring is not found.
Example
 str = 'hello dsl'
 add_rsp_header('string-find()-start', tostring(get(find(str, 'dsl'), 1)))
 str = 'hello dsl 12'
 add_rsp_header('string-find()-end', tostring(get(find(str, 'dsl'), 2)))
 str = 'hello dsl'
 add_rsp_header('string-find()-tail-start', tostring(get(find(str, 'dsl', -6), 1)))
 str = 'hello dsl 12'
 add_rsp_header('string-find()-tail-end', tostring(get(find(str, 'dsl', -6), 2)))
Output:
string-find()-start:7
string-find()-end:9
string-find()-tail-start:7
string-find()-tail-end:9

trim

ItemDescription
Syntaxtrim(s, [, loc])
DescriptionRemoves all whitespace characters at the beginning or at the end of the string specified by the s parameter, and returns a string with the specified whitespace characters removed.
Parameter
  • s: the string.
  • loc: This parameter is optional. Default value: both. Valid values:
    • both: removes the whitespace characters before and after the string.
    • left: removes only the whitespace characters before the string.
    • right: removes only the whitespace characters after the string.
Return valueA string with the specified whitespace characters removed.
Example
say(concat('trim():', trim(' abcd ')))
say(concat('trim(left):', trim(' abcd ', 'left')))
say(concat('trim(right):', trim(' abcd ', 'right')))
Output:
trim():abcd
trim(left):abcd
trim(right): abcd