cancel
Showing results for 
Search instead for 
Did you mean: 

HowTo: TrafficScript String Manipulation

Most of the data manipulation you'll do with TrafficScript will involve manipulating strings. Here is a quick account of the most useful string functions.

 

Strings are managed efficiently within the TrafficScript runtime engine, and memory copies are kept to a minimum.

 

Creating and concatenating strings

 

Assign a string to a variable:

 

1
$password = "Secret";

 

Many functions take strings as arguments, and return strings as values:

 

1
$host = http.getHeader( "Host" ); 

 

Concatenate strings with the '.' operator:

 

1
2
$greeting = "Hello, ".$name
$link = "<a href=\"".$url."\">Click here";<a> 

 

Basic string functions

 

The length of a string:

 

1
$len = string.len( $mystring );

 

Skip or drop bytes off the start or end of a string:

 

1
2
3
4
5
$interpreter = "#!/bin/sh"
$str = string.skip( $interpreter, 2 ); # returns "/bin/sh" 
   
$greeting = "Hello, world!..."
$msg = string.drop( $greeting, 4 ); # returns "Hello, world" 

 

Remove whitespace from the start and end of a string:

 

1
2
$email = [email protected]  "
$email = string.trim( $email );  # returns "[email protected]"

 

The string.substring() function returns a substring from a string:

 

1
2
3
4
$time = "09:15:45"
$hr  = string.substring( $time, 0, 2 );  # returns "09" 
$min = string.substring( $time, 3, 2 );  # returns "15" 
$sec = string.substring( $time, 6, 2 );  # returns "45" 

 

String tests

 

The following functions test the contents of a string:

 

1
2
3
4
5
6
7
8
9
10
11
12
if( string.startsWith( $url, "http://" ) ) { 
   ... # $url begins "http://
   
if( string.endsWith( $url, ".php" ) ) { 
   ... # url ends ".php" 
   
if( string.contains( $url, "/.." ) ) { 
   ... # url contains "/.." 

 

The string.find() function searches for a substring and returns its location:

 

1
2
3
4
$greeting = "Hello, world!"
$i = string.find( $greeting, "llo" );   # returns 2 
$j = string.find( $greeting, "Hello" ); # returns 0 
$k = string.find( $greeting, "name" );  # returns -1 (not found) 

 

String compares can be performed with the '==', '!=', '<', '>', '<=' and '>=' operators:

 

1
2
3
if( $protocol <= "1.0" ) { 
  ... 
}

 

Note that TrafficScript's Type Casting Rules can affect the behaviour of a compare operation:

 

1
2
3
4
5
6
7
8
9
10
11
$count = "100"
   
# Do a string compare 
if( $protocol < "99" ) { 
   ...  
   
# Do an integer compare 
if( $protocol < 99 ) { 
   ... 
}

 

The string.cmp() and string.icmp() functions perform case sensistive and case insensitive string compares, returning negative, zero or positive values. Both arguments are converted to strings if necessary:

 

1
2
3
4
5
6
7
8
if( string.cmp( $protocol, "1.0" ) < 0 ) { 
   ... 
   
# This is identical 
if( string.icmp( $protocol, 1.0 ) < 0 ) { 
   ... 
}

 

String matching and substitution

 

The string.wildmatch() function performs a shell-like wildcard match on a string. The character '?' matches any single character, and '*' matches any substring:

 

1
2
3
4
$url = http.getPath(); 
if( string.wildmatch( $url, "/cgi-bin/*.cgi" ) ) { 
   ... # is a request for a CGI script, without pathinfo 
}

 

Regular expression matching can be performed with the string.regexMatch() function. Stingray uses the standard PCRE regular expression syntax, and matches are placed in the magic $1 to $9 variables:

 

1
2
3
4
$id = "user=Joe, password=Secret"
if( string.regexmatch( $id, "^user=(.*), password=(.*)$" ) ) { 
   log.info( "Got UserID: ".$1.", Password: ".$2 ); 

 

Perform case-insensitive regular expression matches using the optional third function argument:

 

1
string.regexmatch( $username, "joe", "i" );

 

Regular expression substitutions are the easiest and most powerful way to perform complex string manipulation. Text in a string which matches the regular expression is replaced by the substitution:

 

1
2
# Rewrite requests for "/secure/something" to "/private/something" 
$url = string.regexsub($url, "^/secure", "/private"); 

 

Normally, only the first match is replaced; the optional "g" flag indicates that a 'global' replace should be performed, where every match is replaced.

 

1
2
3
4
5
# The document contains references to "oldsite.example.com";  
# replace these with "newsite.enterprise.com" 
$response = http.getResponseBody(); 
$response = string.regexsub( $response, "oldsite.example.com", "newsite.example.com", "g" ); 
http.setResponseBody( $response ); 

 

String encoding and decoding

 

Convert between case using string.toUpper() and string.toLower():

 

1
2
3
$string = "AbCdEfG"
$upper = string.toUpper( $string ); # returns "ABCDEFG" 
$lower = string.toLower( $string ); # returns "abcdefg"

 

HTML-encode a string for safe rendering in a browser using string.htmlEncode(); use string.htmlDecode() to reverse the operation:

 

1
2
3
4
5
$xss = "
<script type="mce-no/type">//
alert('Hello!');
// </script>
"; # This returns "<script>alert('Hello!');</script>" $safe = string.htmlencode( $xss );

 

%-encode control characters, spaces and '%' in a string using string.escape(); use string.unescape() to reverse the operation:

 

1
2
# returns "Hello%20World!%0D%0A" 
$str = string.escape( "Hello World!\r\n" );

 

You may want to manually replace incidences of "&", "?" and "=" with their %-encoded counterparts if you want to use the result in a URL.

 

Use Base64 encoding for a more universal encoding scheme: string.base64encode() and string.base64decode() encode and decode strings. Base64 is used for MIME-encoded messages, and in the HTTP Basic Authorization header.

 

1
2
3
# Encodes a username and password for HTTP BASIC authentication 
$enc = string.base64encode( "userSmiley Tongueasswd" ); 
http.setHeader( "Authorization", "Basic ".$enc );

 

An alternative pair of functions would be string.hexEncode() and string.hexDecode().

 

Finally, you can encrypt and decrypt strings using a passphrase and the AES cipher:

 

1
2
$encrypted = string.encrypt( $plaintext, $passphrase ); 
$plaintext = string.decrypt( $encrypted, $passphrase ); 

 

Read more: Collected Tech Tips: TrafficScript examples

Version history
Revision #:
1 of 1
Last update:
‎02-24-2013 05:51:AM
Updated by:
 
Labels (1)