“Secret” of str_replace()

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]);
}
?>

Tags:

2 Responses to ““Secret” of str_replace()”

  1. ghprod Says:

    Thnx bro :)

    keren bgt tutznya :D

  2. admin Says:

    Thank you bro :D

Leave a Reply