PHP: variables in strings without concatenation

2020-05-21 03:13发布

If I have a variable $var in this string: echo "Hello, there are many $vars";

Php looks for the variable $vars instead of $var.

Without concatenation like: "Hello, there are many $var" . "s";
is there another way to do this, like some sort of escaping character?

标签: php string
4条回答
甜甜的少女心
2楼-- · 2020-05-21 03:52

Alternatively you may want to look at sprintf: http://php.net/manual/en/function.sprintf.php

The sprintf function allows you to format any type of variable as a string in a specific notation.

查看更多
聊天终结者
3楼-- · 2020-05-21 03:56

You can use {} to escape your variable properly. Consider the following example:

echo "There are many ${var}s"; #Or...
echo "There are many {$var}s";

Working example

查看更多
何必那么认真
4楼-- · 2020-05-21 03:59

In php you can escape variables like so

echo "Hello, ${var}'s head is big";

or like

echo "Hello, {$var}'s head is big";

Reference here under escape character section

查看更多
可以哭但决不认输i
5楼-- · 2020-05-21 04:02

Personally I always divide the variables from a string like this: echo 'Hello, there are many '.$var.'s';

Mostly because of readability, if you go through your code it's instantly clear where the variables are.

查看更多
登录 后发表回答