View Full Version : Help me on preg_replace i'm working on

01-10-2012, 12:12 PM
Please i'm writing a program using a regular expression .
Now , i created a string called 'this is a test' and i want to replace 'test' with 'assignment', i try this code but not working , can someone help me
Here is the code

$string='this is a test';
$preg_replace= preg_replace('/[a-zA-Z]/','assignment', $string);
echo $preg_replace;

[ ?>]

Clement Osei

01-10-2012, 02:05 PM
No reason to use preg_replace for a simple replacement like that.

$string='this is a test';
echo str_replace('test','assignment',$string);

01-10-2012, 02:20 PM
Hi Sir,,
Thanks very much for your reply.
Well , i do know how to use the str_replace but want to know using preg_replace.

Please can you help me out ,using the example above.

Thanks Much.

Clement Osei

01-10-2012, 02:51 PM
For simple ones like your example, str_replace is a LOT faster (processing wise).

Regular expressions should only be used to match patterns - something you don't know specifically the value of, or a pattern you need to replace (like parsing BB code).

In other words, learn how to use it with its proper designed application.

01-10-2012, 02:56 PM
Hi Sir,
Thanks for your advise.
I really appreciate it..!!

Clement Ose1