Crmgo Blog

Asterisk: Working with String and Mathematical Operations

Asterisk: Working with String and Mathematical Operations

String manipulation functions The ${LEN(foo)} function returns the length of the string foo. For example, exten => 100,1,Set(Fruit=pear) exten => 100,2,NoOp(${LEN(Fruit)}) exten => 100,3,NoOp(${LEN(${Fruit})}) The first NoOp command should display the value 5 (the length of the string "pear"). The second NoOp command should display the value 4...

Asterisk: Working with String and Mathematical Operations

String Manipulation Functions

String Length

${LEN(foo)}

returns the length of the string foo. For example,

exten => 100,1,Set(Fruit=pear)
exten => 100,2,NoOp(${LEN(Fruit)})
exten => 100,3,NoOp(${LEN(${Fruit})})

the first NoOp command should display the value 5 (the length of the string "pear"). The second NoOp command should display the value 4 (the length of the string "pear").

This method allows for excellent checking of empty strings and variables containing NULL.

Substrings

${foo:offset:length}

returns a substring of foo, starting at offset and limiting the returned string to length characters.

  • If offset is negative, the offset is counted from the end of the string rather than the beginning.
  • If length is omitted or negative, the returned string is not limited in size and will return the entire string starting from offset.

Examples:

${123456789:1} - returns the string 23456789
${123456789:-4} - returns the string 6789
${123456789:0:3} - returns the string 123
${123456789:2:3} - returns the string 345
${123456789:-4:3} - returns the string 678

Usage example:

exten => _NXX.,1,Set(areacode=${EXTEN:0:3}) - gets the first 3 digits from the ${EXTEN} variable
exten => _516XXXXXXX,1,Dial(${EXTEN:3}) - gets the value of the ${EXTEN} variable after the first 3 digits
exten => 100,1,Set(whichVowel=4)
exten => 100,2,Set(foo=AEIOU:${whichVowel}:1) - the ${foo} variable will have the value 'U'

String Concatenation

To concatenate two strings, simply write the directives as shown below:

${foo}${bar}
555${theNumber}
${longDistancePrefix}555${theNumber}

Mathematical Operations on Variables

For mathematical operations on variables, such as increment, multiplication, addition, simply write:

exten => s,1,Set(SOMEVAR=$[${SOMEVAR} + 1]) ; increment
exten => s,2,Set(SOMEVAR=$[2 * ${SOMEVAR}]) ; multiplication, etc.
You must use spaces in expressions as shown above.

Starting with Asterisk release 1.2, the MATH function is also available...

exten => s,1,Set(SOMEVAR=${MATH(${SOMEVAR}+1)}) ; increment
exten => s,2,Set(SOMEVAR=${MATH(2*${SOMEVAR})}) ; multiplication, etc.

Notes on Various Versions

  • The CALLINGPRES variable was added to CVS HEAD on 2004-09-10, included in Asterisk 1.2 release
  • The TOUCH_MONITOR variable was added to CVS HEAD on 2005-01-05, included in Asterisk 1.2 release

Note: This post may be AI-assisted and then human-edited. Editorial responsibility: Dmytro Lomaka, Kaltenkirchen.