一起源码网

  • www.171739.xyz
  • 全球最大的互联网技术和资源下载平台
搜索
猜你喜欢
查看: 5149|回复: 1
打印 上一主题 下一主题

php中字符串的拼接用法详解

[复制链接]

0

主题

0

帖子

1万

积分

钻石会员

Rank: 8Rank: 8

积分
17424
QQ
跳转到指定楼层
楼主
发表于 2020-3-9 03:30 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
首先和大家说下,学习任何一门语言都要去官网去看文档,因为官方的文档正确性有保证,并且也最有广泛性。

有两个()。第一个是连接运算符(“.”),它返回其左右参数连接后的字符串。第二个是连接(“.=”),它将右边参数附加到左边的参数之后。

<?php
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"

$a = "Hello ";
$a .= "World!";     // now $a contains "Hello World!"
?>
<?php
    $var = 3;
    echo "Result:" . $var + 3;
?>

运行后发现只输出了一个 ‘3’,为什么呢? 因为第一字符串“Result3”被创建,这然后被添加到3得到3,非空非数字字符串被转换为0。如果要输出"Result: 6",则代码如下:

<?php
    $var = 3;
    echo "Result:" . ($var + 3);
?>

下面的例子---如果试图用连接运算符加号,你的结果将是这些数字为字符串的结果。

<?php

echo "thr"."ee";           //prints the string "three"
echo "twe" . "lve";        //prints the string "twelve"
echo 1 . 2;                //prints the string "12"
echo 1.2;                  //prints the number 1.2
echo 1+2;                  //prints the number 3

?>

大括号服务好替代串联,和他们更快地输入和代码看起来更干净。记得用双引号(“”)而不是单引号(‘’)作为其内容是由PHP parced,因为在单引号(''),你会得到所提供的litaral名称

<?php

$a = '12345';

// This works:
echo "qwe{$a}rty"; // qwe12345rty, using braces
echo "qwe" . $a . "rty"; // qwe12345rty, concatenation used

// Does not work:
echo 'qwe{$a}rty'; // qwe{$a}rty, single quotes are not parsed
echo "qwe$arty"; // qwe, because $a became $arty, which is undefined

?>
<?php

$var = "hello";
$world = "world";

echo "$var" . '$world'; //outputs hello$world

echo "$var" . "$world"; //outputs helloworld

echo "$var" .  $world; //outputs helloworld

?>

可以看出使用使用(‘’)即把单引号里的内容作为了字符,直接echo出来了。而使用(“”)则保留了变量。

分享到:  QQ好友和群QQ好友和群
收藏收藏
回复

使用道具 举报

0

主题

17

帖子

157

积分

注册会员

Rank: 2

积分
157
沙发
发表于 2022-9-4 15:50 | 只看该作者
波士顿动力机器人开源代码真假
回复

使用道具 举报

一起源码让程序更轻更快

www.171739.xyz

工作时间 周一至周六 8:00-17:30

侵权处理

客服QQ点击咨询

关注抖音号

定期抽VIP

Copyright © 2016-2021 https://www.171739.xyz/ 滇ICP备13200218号

快速回复 返回顶部 返回列表