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:

$password = "Secret";

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

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

Concatenate strings with the '.' operator:

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

Basic string functions

The length of a string:

$len = string.len( $mystring );

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

$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:

$email = "  foo@example.com  ";
$email = string.trim( $email );  # returns "foo@example.com"

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

$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:

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:

$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:

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

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

$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:

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:

$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. ZXTM uses the standard PCRE regular expression syntax, and matches are placed in the magic $1 to $9 variables:

$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:

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:

# 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.

# 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():

$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:

$xss = "<script>alert('Hello!');</script>";
# This returns "&lt;script&gt;alert('Hello!');&lt;/script&gt;"
$safe = string.htmlencode( $xss );

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

# 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.

# Encodes a username and password for HTTP BASIC authentication
$enc = string.base64encode( "user:passwd" );
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:

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

Further Information

For a full function reference, refer to section 6.1 of the ZXTM 3.1 TrafficScript Manual.

Owen Garrett [Zeus Dev Team] 28 July 2005  Permalink  
Leave a comment ...
Your email address will not be displayed.
Your URL will be displayed.
This public messageboard is not a forum for technical support. To report technical support problems, please contact our dedicated Support team using the instructions at the bottom of this page.
Options:
 
(Line breaks become <br />)
(Set cookies for name, email & url)
Download Free ZXTM Desktop Edition

Recent Articles

Other Resources



www.zeus.com