str_replace() - String Replace without RegExp

In perl one would replace string without putting much thought into it. You use use the code '$str =~ s/replace_this/with_this/g;' - this is a very efficient and easy way to replace a string. However this statement uses regular expression - which is much more processor intensive than a simple string replace. In many situations I have faced, I had to use a regular expression replace where a string replace would be better. That is because perl don't have a function to do a string replace.

So I have decided to make one for myself...

Code

#Replace a string without using RegExp.
sub str_replace {
	my $replace_this = shift;
	my $with_this  = shift; 
	my $string   = shift;
	
	my $length = length($string);
	my $target = length($replace_this);
	
	for(my $i=0; $i<$length - $target + 1; $i++) {
		if(substr($string,$i,$target) eq $replace_this) {
			$string = substr($string,0,$i) . $with_this . substr($string,$i+$target);
			return $string; #Comment this if you what a global replace
		}
	}
	return $string;
}

Useage

string str_replace ( string search, string replace, string subject );

The function uses the same format as the str_replace() function of PHP. The first argument is the search string that is to be replaced, the second argument is the string that it must be replaced with and the third argument is the string in which the replacement must be done. The result will be returned.

Example

$str_regreplace = "Hello World";
$string = "Hello World";
print $string . "\n\n";
$str_regreplace =~ s/Hello/Goodbye/; #Prints 'Goodbye World'
print $str_regreplace . "\n";

print str_replace('Hello','Goodbye',$string);  #Prints 'Goodbye World'

Is there a better way to do this?

blog comments powered by Disqus
Subscribe to Feed