Monday, August 18, 2008

PHP's str_replace in Actionscript 3.0

PHP has a robust method for doing a string search and replace. The str_replace method can take in an array of elements to be searched and replaced and do the replace in one shot. Check out PHP's str_replace function's manual for details.

I just put together a TextUtils class with my Actionscript implementation of str_replace.

TextUtils.as

You can use it like below:
var content:String = "hello world";
trace(TextUtils.str_replace(["h","w"],["H","W"], content))
//outputs 'Hello World'
It gets interesting, when you gotta do something like this:
var content:String = "h.e.l.l.o; w,o,r,l,d";
trace(TextUtils.str_replace([",", ".", ";"], "", content))
//outputs 'hello world'

If you find it useful, go ahead and use it.

Of course, Actionscript 3.0 does have its own implementation of 'replace' function in the String class, which is pretty sleek as well. It also includes support for Regular Expression based search and replace. Check out the documentation AS3.0 String.replace here.
Post a Comment