Variable Manipulation and String Operations

Call Handling Asterisk 18+ -- Last reviewed 2026-03-29 variables set dialplan string-operations call-handling Found this useful? Upvote it. ×

Variable Manipulation and String Operations

The Set() application assigns and manipulates channel variables. Combined with Asterisk's string slicing syntax, it handles digit stripping, caller ID manipulation, and conditional routing.

Basic Variable Assignment

[examples]
exten => 6009,1,Set(COUNT=3)
 same => n,SayNumber(${COUNT})
 same => n,Set(COUNT=10)
 same => n,SayNumber(${COUNT})

String Slicing: Strip Prefix Digits

[outbound]
; Strip the leading 9 from 9NXXXXXXX (access code dialing)
exten => _9NXXXXXXX,1,Set(number=${EXTEN:1})
 same => n,Dial(PJSIP/trunk/${number})

; Strip a 3-digit prefix: 1015551234 -> 5551234
exten => _101XXXXXXX,1,Set(number=${EXTEN:3})
 same => n,Dial(PJSIP/trunk/${number})

String Slicing: Extract Parts

[examples]
; Get the last 4 digits of a 10-digit number
exten => _NXXXXXXXXX,1,Set(last4=${EXTEN:-4})

; Get the area code (first 3 digits)
 same => n,Set(areacode=${EXTEN:0:3})

; Get digits 4 through 6
 same => n,Set(exchange=${EXTEN:3:3})

 same => n,Verbose(1,Area: ${areacode} Exchange: ${exchange} Line: ${last4})

Variable Scope and Inheritance

[internal]
; Local variable -- only on this channel
exten => _1XXX,1,Set(LOCAL_VAR=hello)

; Single underscore -- inherits one level to the outbound channel
 same => n,Set(_INHERIT_ONCE=world)

; Double underscore -- inherits to all child channels recursively
 same => n,Set(__INHERIT_ALWAYS=foo)
 same => n,Dial(PJSIP/${EXTEN})

How it works

  1. ${EXTEN:offset}: Slices the string starting at offset. ${EXTEN:1} removes the first character (digit 9 in 9NXXXXXXX). ${EXTEN:3} removes the first three characters.
  2. ${EXTEN:offset:length}: Extracts length characters starting at offset. ${EXTEN:0:3} gets the first 3 digits. ${EXTEN:3:3} gets digits 4-6.
  3. ${EXTEN:-N}: Negative offset counts from the end. ${EXTEN:-4} returns the last 4 characters.
  4. Variable inheritance: No prefix: variable is local to the current channel. _ prefix: inherits one level (to the channel created by Dial). __ prefix: inherits to all child channels and their children. This is critical for features like DYNAMIC_FEATURES and CALLERID overrides.
  5. Pattern matching: _9NXXXXXXX matches a 9 followed by a number 2-9 then 7 digits. X matches 0-9, Z matches 1-9, N matches 2-9, . matches one or more of anything, ! matches one or more.

Tips

User Notes

No notes yet. Be the first to contribute a tip or example.

Contribute a note

Share a tip, gotcha, or practical example. Keep it under 2000 characters. No questions (use the Asterisk community forums for support). Wrap code in backticks.

Moderated before publishing. Email never shown.

Related Snippets