faqts : Computers : Programming : Languages : PHP : Common Problems : Strings

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

18 of 20 people (90%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

How can I search $a for ##rand## and replace every occurence of ##rand## in $a with $b?

May 7th, 2001 17:54
Philip Olson, Mike G., Ben Udall,


Consider using the php function str_replace :
  PHP Manual : str_replace()                       :
  --------------------------------------------------
  http://www.php.net/manual/function.str-replace.php
A similar way to explain this is :
  $new_string = str_replace($find_me,$replace_with_me,$input_string);
To explain :
  - $new_string      : Returned modified version of $input_string as 
                       per our use of str_replace().  
  - $find_me         : Each instance of $find_me will be replaced 
                       with the contents of $replace_with_me
  - $replace_with_me : Will replace each instance of $find_me
  - $input_string    : Our input.  The contents of this string will
                       be modified and outputted as $new_string. 
Here's an example that will hopefully explain your question :
 <?php
   $a = 'Today I like the color : ##rand##';
   $b = 'blue';
   $new_string = str_replace('##rand##',$b,$a);
   echo $new_string; // Today I like the color : blue
 ?>
Perhaps it'll end up looking like this :
 <?php
   $colors = array('blue','green','red','yellow');
   srand ((double) microtime() * 1000000); 
   $key = rand (0,sizeof($colors)-1);
   $words = 'The color {color} will make you happy today.';
   $color = '<font color="'.$colors[$key].'">'.$colors[$key].'</font>'; 
   $words = str_replace('{color}',$color,$words);
   print $words;
 ?>
If you plan on using Regular Expressions, consider the following :
  http://www.php.net/manual/en/function.preg-replace.php
  http://www.php.net/manual/en/function.ereg-replace.php
Note: str_replace() will ALWAYS be faster, only use *regex* functions 
if you must/need to.