how to replace a placeholder in a string?

后端 未结 4 1999
臣服心动
臣服心动 2021-01-08 01:06

Not very sure how to word this question but I\'ll give an example.

$string = \'Hey, $name. How are you?\'; 

When I post this string,

相关标签:
4条回答
  • You can use place-holders and str_replace. Or use PHP's built-in sprintf and use %s. (And as of v4.0.6 you can swap the ordering of arguments if you'd like).

    $name = 'Alica';
    
    // sprintf method:
    $format = 'Hello, %s!';
    echo sprintf($format, $name); // Hello, Alica!
    
    // replace method:
    $format = "Hello, {NAME}!";
    echo str_replace("{NAME}", $name, $format);
    

    And, for anyone wondering, I understood that is trouble templating a string, not PHP's integrated concatenation/parsing. I just assume keep this answer up though as I'm still not 100% sure this OP's intent

    0 讨论(0)
  • 2021-01-08 01:21

    I've always been a fan of strtr.

    $ php -r 'echo strtr("Hi @name. The weather is @weather.", ["@name" => "Nick", "@weather" => "Sunny"]);'
    Hi Nick. The weather is Sunny.
    

    The other advantage to this is you can define different placeholder prefix types. This is how Drupal does it; @ indicates a string to be escaped as safe to output to a web page (to avoid injection attacks). The format_string command loops over your parameters (such as @name and @weather) and if the first character is an @, then it uses check_plain on the value.

    0 讨论(0)
  • 2021-01-08 01:25

    A third solution, no better or worse than the aforementioned, is concatenation:

    echo 'Hello '. $name .'!!!';

    0 讨论(0)
  • 2021-01-08 01:28

    You should be wrapping the string in double quotes (") if you want variables to be expanded:

    $name = "Alica";
    $string = "Hey, $name. How are you?"; // Hey, Alica. How are you?
    

    See the documentation.

    0 讨论(0)
提交回复
热议问题