php中字符串的拼接

  最近由于数据库大作业的到来,我又不得不去搞php+mysql了,对mysql的使用也就仅限能正确使用“增”,“删”,“改”,“更”了。而实际上也只需要会这么点,最难的还是php的编写。之前一直没认真研究php,今天实在没办法了,发现php中字符串的拼接用的实在是太多了。所以特意去研究了一发,整理下笔记。


   首先和大家说下,学习任何一门语言都要去官网去看文档,因为官方的文档正确性有保证,并且也最有广泛性。这里就给出官方的文档链接http://php.net/manual/zh/language.operators.string.php#41950。如果有登不上的,就继续往下看我的笔记吧。


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

<?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出来了。而使用(“”)则保留了变量。


  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值