how to replace a placeholder in a string?

后端 未结 4 2041
臣服心动
臣服心动 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条回答
  •  不要未来只要你来
    2021-01-08 01:11

    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

提交回复
热议问题