php裡面字串操作,使用 的方法

2021-03-31 16:41:19 字數 3033 閱讀 3186

當用雙引號或者定界符指定字串時,其中的變數會被解析。

有兩種語法,一種簡單的和一種複雜的。簡單語法最通用和方便,它提供了解析變數,陣列值,或者物件屬性的方法。

複雜語法是 php 4 引進的,可以用花括號括起乙個表示式。

簡單語法

如果遇到美元符號($),解析器會盡可能多地取得後面的字元以組成乙個合法的變數名。如果你想明示指定名字的結束,用花括號把變數名括起來。

<?php

$beer

= 'heineken'

;echo

"$beer's taste is great"

; // works, "'" is an invalid character for varnames

echo

"he drank some $beers"

;   

// won't work, 's' is a valid character for varnames

echo

"he drank some $s"

; // works

echo

"he drank some s"

; // works

?>

同樣也可以解析陣列索引或者物件屬性。對於陣列索引,右方括號(])標誌著索引的結束。物件屬性則和簡單變數適用同樣的規則,儘管對於物件屬性沒有像變數那樣的小技巧。

<?php

// these examples are specific to using arrays inside of strings.

// when outside of a string, always quote your array string keys

// and do not use when outside of strings either.

// let's show all errors

error_reporting

(e_all

);$fruits

= array(

'strawberry'

=>

'red'

, 'banana'

=>

'yellow'

);// works but note that this works differently outside string-quotes

echo

"a banana is $fruits[banana]."

;// works

echo

"a banana is ."

;// works but php looks for a constant named banana first

// as described below.

echo

"a banana is ."

;// won't work, use braces.  this results in a parse error.

echo

"a banana is $fruits['banana']."

;// works

echo

"a banana is "

. $fruits

['banana'

] .

".";

// works

echo

"this square is $square->width meters broad."

;// won't work. for a solution, see the ***plex syntax.

echo

"this square is $square->width00 centimeters broad."

;?>

對於任何更複雜的情況,應該使用複雜語法。

複雜(花括號)語法

不是因為語法複雜而稱其為複雜,而是因為用此方法可以包含複雜的表示式。

事實上,用此語法你可以在字串中包含任何在名字空間的值。僅僅用和在字串之外同樣的方法寫乙個表示式,然後用 把它包含進來。因為不能轉義「

echo

"this is "

;// 可以,輸出為:this is fantastic

echo

"this is "

;echo

"this is $"

;// works

echo

"this square is 00 centimeters broad."

;// works

echo

"this works: "

;// this is wrong for the same reason as $foo[bar] is wrong

// outside a string.  in otherwords, it will still work but

// because php first looks for a constant named foo, it will

// throw an error of level e_notice (undefined constant).

echo

"this is wrong: "

;// works.  when using multi-dimensional arrays, always use

// braces around arrays when inside of strings

echo

"this works: "

;// works.

echo

"this works: "

. $arr

['foo'][3

];echo

"you can even write "

;echo

"this is the value of the var named $name: }"

;?>

php字串操作

一空格特殊字元 1 string trim string str string charlist 去除字串開始結尾位置的空格和特殊字元 如果沒有第二個引數只去除空格 2 string ltrim string str string charlist 去除字串開始位置的空格和特殊字元 3 string...

PHP 字串操作

可以使用trim 函式去除字串開始位置和結束位置的空格,並把結果字串返回。預設情況下,去除 n r t xob 0和空格。也可以傳入第二個引數提供要過濾的特殊字元。ltrim 只從字串開始處去除,rtrim 只從字串結束處去除。nl2br 函式將會把字串中的換行符替換為 標記。當字串中含有一些有問題...

php字串操作

一空格特殊字元 1 string trim string str string charlist 去除字串開始結尾位置的空格和特殊字元 如果沒有第二個引數只去除空格 2 string ltrim string str string charlist 去除字串開始位置的空格和特殊字元 3 string...