Helping ordinary people create extraordinary websites!

Choosing The Right Server-Side Scripting Language

By Craig McElwee
2004-01-06

Task 3: Search and Replace
Data input on HTML forms frequently need to be modified, and if you intend to run a shell command using data input from the user, then it is an absolute necessity! You must cleanse all input data of anything that might compromise the integrity of your system.

Perl has the most powerful regular expression engine and excels at text manipulation. If your next program requires much text manipulation, you'll be hard pressed to find a reason not to use Perl. That said, Python, PHP, and Tcl support regular expression searching and replacing, though the interface in each appears awkward and convoluted when compared to Perl's elegant syntax. Here are examples from the scripts, modified so each uses the same simple variable name for clarity. In each example, a case-insensitive search for the sequence of letters "cat" is made in the value of the variable 'data', and for each successful find, those letters are replaced with the sequence "dog":

Perl:


$data =~ s/cat/dog/gi;


PHP:


$data = eregi_replace("cat","dog",$data);

Python:
 


data = regsub.gsub("cat", "dog", data)

Tcl:


regsub -all -nocase {cat} $data {dog}
data



The Java language lacks integrated regular expressions, but this is a rather simple substitution that we can manage with substrings:

Java:


String findString = new String("cat");
String

replaceString = new String("dog");

int x = data.indexOf(findString);
while(x != -1)


{
data = new String(data.substring(0,x)
+ replaceString
+ data.substring(x+

findString.length()));
x = sourceString.indexOf(findString);
}


This is extremely inelegant. We could have worked similar solutions in the other languages, but a clear, concise, single statement seems far superior. For whatever reason, Sun decided to leave regular expressions out of the standard Java distribution.



Tutorial pages:

First published by IBM developerWorks


 1 Votes

You might also want to check these out:


Leave a Comment on "Choosing The Right Server-Side Scripting Language"
You must be logged in to post a comment.

Link to This Tutorial Page!


GET OUR NEWSLETTERS