Choosing The Right Server-Side Scripting Language
By Craig McElwee
2004-01-06
Reader Rating:

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:
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.
First published by IBM developerWorks
If you found this article interesting, you may want to read these as well:
» Protecting your PHP and HTML Source Code
» Publishing Newsletters Using PHP & MySQL - 4
» Publishing Newsletters Using PHP & MySQL - 3
» Publishing Newsletter Using PHP & MySQL - 2
» Publishing Newsletters Using PHP & MySQL
» Unix Webserver Crontab Basics
|