Thursday, May 5, 2011

How to replace a variable within a string with PHP?

So I have some PHP code that looks like:

$message = 'Here is the result: %s';

I just used %s as an example. It's basically a placeholder for whatever will go there. Then I pass the string to a function and I want that function to replace the %s with the value.

What do I need to do to achieve this? Do I need to do some regex, and use preg_replace(), or something? or is there a simpler way to do it?

From stackoverflow
  • try dynamic variables:

    $placeholder = 's';
    str_replace("%".$placeholder,$$placeholder,$message);
    

    then %s will be replaced with $s, the variable

  • You can use str_replace

    http://es.php.net/manual/en/function.str-replace.php

    that is for sure lighter than regex.

    Also sprintf can be an even more versatile option

    http://es.php.net/manual/en/function.sprintf.php

  • You can use sprintf, which works in a very similar way to C's printf and sprintf functions.

  • You can actually use sprintf function which will return a formatted string and will put your variables on the place of the placeholders.
    It also gives you great powers over how you want your string to be formated and displayed

    $output = sprintf("Here is the result: %s for this date %s", $result, $date);
    
  • If you use %s, I think that is the same placeholder that printf uses for a string. So you could do:

    $text = sprintf($message, "replacement text");
    

    Think that should work at least...

  • 
    $find = array(
         '#name#',
         '#date#'
    );
    $find = array(
         'someone\'s name',
         date("m-d-Y")
    );
    $text_result = str_replace($find, $search, $text);
    

    I'm usually using this for my code, fetching the $text from some text/html files then make the $text_result as the output

0 comments:

Post a Comment