Home > Programming > “Secret” of str_replace()

“Secret” of str_replace()

June 26th, 2008

Let’s check this PHP code

<?php
$s = 'hello world';
$s = str_replace('o', my_get_string(), $s);
echo($s);

function my_get_string() {
   $q = mysql_query('SELECT VERSION()');
   $r = mysql_fetch_array($q);
   return($r[0]);
}
?>

Basically my_get_string() is a function that return some string.

Now the question is : is the above code efficient? Let’s check.

<?php
$s = 'hellx wxrld';// note that we have no 'o' here to be replaced
$s = str_replace('o', my_get_string(), $s);
echo($s);

function my_get_string() {
   $q = mysql_query('SELECT VERSION()');
   $r = mysql_fetch_array($q);
   echo('<p>I am on my_get_string()</p>');// just a simple message
   return($r[0]);
}
?>

Run the code above, and you still see the simple message although your string does not contain “o”.

What if your “my_get_string()” contains lot of rows and steps, for example extracting data from table, replacing it with current time, etc etc. Your script’ll waste its time with executing the whole my_get_string() although does not contain “o”. So only perform the replacement only IF your string contains the string that will be replaced.

<?php
$s = 'hellx wxrld';// note that we have no 'o' here to be replaced
if (stristr($s, 'o'))
   $s = str_replace('o', my_get_string(), $s);
echo($s);

function my_get_string() {
   $q = mysql_query('SELECT VERSION()');
   $r = mysql_fetch_array($q);
   echo('<p>I am on my_get_string()</p>');// just a simple message
   return($r[0]);
}
?>

Programming

 
Your Ad Here
 
  1. July 31st, 2008 at 02:35 | #1

    Thnx bro :)

    keren bgt tutznya :D

  2. July 31st, 2008 at 19:26 | #2

    Thank you bro :D

  1. No trackbacks yet.