PHP字符串總結(jié)

定義:一個(gè)字符串 string 就是由一系列的字符組成,其中每個(gè)字符等同于一個(gè)字節(jié)。這意味著 PHP 只能支持 256 的字符集,因此不支持 Unicode 。相信很多新手在官網(wǎng)看到這句話的時(shí)候都會(huì)覺(jué)得很疑惑,明明PHP不是可以打印出中文嗎?為什么會(huì)說(shuō)字符串不支持Unicode呢?實(shí)際上,這句話應(yīng)該這樣理解:字符串會(huì)原生支持ascii字符集,會(huì)直接保存不進(jìn)行編碼,但是對(duì)于其他字符集會(huì)自動(dòng)根據(jù)文檔的編碼來(lái)進(jìn)行編碼,所以如果文檔的編碼設(shè)置正確的話,是可以正確將保存在字符串里面的編碼正確讀取出來(lái)的。

常用函數(shù)
因?yàn)樽址暮瘮?shù)非常多,我粗略的數(shù)了一下,接近100個(gè),所以想要都記住是不太現(xiàn)實(shí)的,只能把常用記住,其他需要用到的時(shí)候再來(lái)看手冊(cè)吧。


連接與分割

1.explode — 使用一個(gè)字符串分割另一個(gè)字符串

用法:

array explode ( string $delimiter , string $string [, int $limit ] )

示例:

$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

2.implode — 將一個(gè)一維數(shù)組的值轉(zhuǎn)化為字符串

用法:

string implode ( string $glue , array $pieces )

示例:

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);

echo $comma_separated; // lastname,email,phone

3.str_split — 將字符串轉(zhuǎn)換為數(shù)組

用法:

array str_split ( string $string [, int $split_length = 1 ] )

示例:

$str = "Hello Friend";

$arr1 = str_split($str);
$arr2 = str_split($str, 3);

print_r($arr1);
print_r($arr2);

//輸出的結(jié)果
Array
(
    [0] => H
    [1] => e
    [2] => l
    [3] => l
    [4] => o
    [5] =>
    [6] => F
    [7] => r
    [8] => i
    [9] => e
    [10] => n
    [11] => d
)

Array
(
    [0] => Hel
    [1] => lo
    [2] => Fri
    [3] => end
)

4.mb_split — 使用正則表達(dá)式分割多字節(jié)字符串

用法:

array mb_split ( string $pattern , string $string [, int $limit = -1 ] )

示例:

To split an string like this: "日、に、本、ほん、語(yǔ)、ご" using the "、" delimiter i used:

     $v = mb_split('、',"日、に、本、ほん、語(yǔ)、ご");

but didn't work.

The solution was to set this before:

       mb_regex_encoding('UTF-8');
      mb_internal_encoding("UTF-8"); 
     $v = mb_split('、',"日、に、本、ほん、語(yǔ)、ご");

and now it's working:

Array
(
    [0] => 日
    [1] => に
    [2] => 本
    [3] => ほん
    [4] => 語(yǔ)
    [5] => ご
)

5.preg_split — 通過(guò)一個(gè)正則表達(dá)式分隔字符串

用法:

array preg_split ( string $pattern , string $subject [, int $limit = -1 [, int $flags = 0 ]] )

示例:

//使用逗號(hào)或空格(包含" ", \r, \t, \n, \f)分隔短語(yǔ)
$keywords = preg_split("/[\s,]+/", "hypertext language, programming");
print_r($keywords);

//輸出
Array
(
    [0] => hypertext
    [1] => language
    [2] => programming
)

6.strstr — 查找字符串的首次出現(xiàn),其忽略大小寫(xiě)版本為stristr

用法:

string strstr ( string $haystack , mixed $needle [, bool $before_needle = false ] )

示例:

$email  = 'name@example.com';
$domain = strstr($email, '@');
echo $domain; // 打印 @example.com

$user = strstr($email, '@', true); // 從 PHP 5.3.0 起
echo $user; // 打印 name

7.strrchr — 查找指定字符在字符串中的最后一次出現(xiàn)

用法:

string strrchr ( string $haystack , mixed $needle )

示例:

$path = '/www/public_html/index.html';
$filename = substr(strrchr($path, "/"), 1);
echo $filename; // "index.html"

8.strpos — 查找字符串首次出現(xiàn)的位置,對(duì)應(yīng)的最后出現(xiàn)的函數(shù)為strrpos

用法:

mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

9.substr — 返回字符串的子串

用法:

string substr ( string $string , int $start [, int $length ] )

示例:

$rest = substr("abcdef", -1);    // 返回 "f"
$rest = substr("abcdef", -2);    // 返回 "ef"
$rest = substr("abcdef", -3, 1); // 返回 "d"

查找與替換

1.preg_match — 執(zhí)行一個(gè)正則表達(dá)式匹配

用法:

int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )

示例:

//從URL中獲取主機(jī)名稱
preg_match('@^(?:http://)?([^/]+)@i',
    "http://www.php.net/index.html", $matches);
$host = $matches[1];//$host為www.php.net

//獲取主機(jī)名稱的后面兩部分
preg_match('/[^.]+\.[^.]+$/', $host, $matches);
echo "domain name is: {$matches[0]}\n";
//輸出domain name is: php.net


Regex quick reference
[abc]     A single character: a, b or c
[^abc]     Any single character but a, b, or c
[a-z]     Any single character in the range a-z
[a-zA-Z]     Any single character in the range a-z or A-Z
^     Start of line
$     End of line
\A     Start of string
\z     End of string
.     Any single character
\s     Any whitespace character
\S     Any non-whitespace character
\d     Any digit
\D     Any non-digit
\w     Any word character (letter, number, underscore)
\W     Any non-word character
\b     Any word boundary character
(...)     Capture everything enclosed
(a|b)     a or b
a?     Zero or one of a
a*     Zero or more of a
a+     One or more of a
a{3}     Exactly 3 of a
a{3,}     3 or more of a
a{3,6}     Between 3 and 6 of a

options: i case insensitive m make dot match newlines x ignore whitespace in regex o perform #{...} substitutions only once

2.preg_replace — 執(zhí)行一個(gè)正則表達(dá)式的搜索和替換,preg_filter()等價(jià)于preg_replace() 除了它僅僅返回(可能經(jīng)過(guò)轉(zhuǎn)化)與目標(biāo)匹配的結(jié)果

用法:

mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )

示例:

$string = 'The quick brown fox jumped over the lazy dog.';
$patterns = array();
$patterns[0] = '/quick/';
$patterns[1] = '/brown/';
$patterns[2] = '/fox/';
$replacements = array();
$replacements[2] = 'bear';
$replacements[1] = 'black';
$replacements[0] = 'slow';
echo preg_replace($patterns, $replacements, $string);

//輸出The bear black slow jumped over the lazy dog.

3.wordwrap — 打斷字符串為指定數(shù)量的字串

用法:

string wordwrap ( string $str [, int $width = 75 [, string $break = "\n" [, bool $cut = false ]]] )

示例:

$text = "A very long woooooooooooord.";
$newtext = wordwrap($text, 8, "\n", true);

echo "$newtext\n";

//輸出
A very
long
wooooooo
ooooord.

4.nl2br — 在字符串所有新行之前插入 HTML 換行標(biāo)記

用法:

string nl2br ( string $string [, bool $is_xhtml = true ] )

5.htmlspecialchars — Convert special characters to HTML entities htmlspecialchars_decode — 將特殊的 HTML 實(shí)體轉(zhuǎn)換回普通字符

用法:

string htmlspecialchars ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = ini_get("default_charset") [, bool $double_encode = true ]]] )

6.htmlentities — Convert all applicable characters to HTML entities

用法:

string htmlentities ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = ini_get("default_charset") [, bool $double_encode = true ]]] )

示例:

$str = "A 'quote' is <b>bold</b>";

// Outputs: A 'quote' is <b>bold</b>
echo htmlentities($str);
//和htmlspecialchars的輸出一樣

// Outputs: A 'quote' is <b>bold</b>
echo htmlentities($str, ENT_QUOTES);

加密

1.md5 — 計(jì)算字符串的 MD5 散列值,md5_file — 計(jì)算指定文件的 MD5 散列值

用法:

string md5 ( string $str [, bool $raw_output = false ] )

2.sha1 — 計(jì)算字符串的 sha1 散列值,sha1_file — 計(jì)算文件的 sha1 散列值

用法:

string sha1 ( string $str [, bool $raw_output = false ] )

3.hash — 生成哈希值 (消息摘要),hash_file — 使用給定文件的內(nèi)容生成哈希值

用法:

string hash ( string $algo , string $data [, bool $raw_output = false ] )

4.crc32 — 計(jì)算一個(gè)字符串的 crc32 多項(xiàng)式

用法:

int crc32 ( string $str )

生成 str 的 32 位循環(huán)冗余校驗(yàn)碼多項(xiàng)式。這通常用于檢查傳輸?shù)臄?shù)據(jù)是否完整。


其他

1.addslashes — 使用反斜線引用字符串

用法:

string addslashes ( string $str )

2.lcfirst — 使一個(gè)字符串的第一個(gè)字符小寫(xiě),ucfirst — 將字符串的首字母轉(zhuǎn)換為大寫(xiě)

用法:

string lcfirst ( string $str )

3.ucwords — 將字符串中每個(gè)單詞的首字母轉(zhuǎn)換為大寫(xiě)

用法:

string ucwords ( string $str )

4.strtoupper — 將字符串轉(zhuǎn)化為大寫(xiě),strtolower — 將字符串轉(zhuǎn)化為小寫(xiě)

用法:

string strtoupper ( string $string )

5.trim — 去除字符串首尾處的空白字符(或者其他字符),ltrim刪除字符串開(kāi)頭的空白字符(或其他字符),rtrim刪除字符串末端的空白字符(或者其他字符)

用法:

string trim ( string $str [, string $charlist = " \t\n\r\0\x0B" ] )

6.sprintf — 返回一個(gè)格式化的字符串

用法:

string sprintf ( string $format [, mixed $args [, mixed $... ]] )
//Possible format values:
%% - Returns a percent sign
%b - Binary number
%c - The character according to the ASCII value
%d - Signed decimal number (negative, zero or positive)
%e - Scientific notation using a lowercase (e.g. 1.2e+2)
%E - Scientific notation using a uppercase (e.g. 1.2E+2)
%u - Unsigned decimal number (equal to or greather than zero)
%f - Floating-point number (local settings aware)
%F - Floating-point number (not local settings aware)
%g - shorter of %e and %f
%G - shorter of %E and %f
%o - Octal number
%s - String
%x - Hexadecimal number (lowercase letters)
%X - Hexadecimal number (uppercase letters)

//Additional format values. These are placed between the % and the letter (example %.2f):

+ (Forces both + and - in front of numbers. By default, only negative numbers are marked)
' (Specifies what to use as padding. Default is space. Must be used together with the width specifier. Example: %'x20s (this uses "x" as padding)
- (Left-justifies the variable value)
[0-9] (Specifies the minimum width held of to the variable value)
.[0-9] (Specifies the number of decimal digits or maximum string length)

7.strcmp — 二進(jìn)制安全字符串比較,strcasecmp — 二進(jìn)制安全比較字符串(不區(qū)分大小寫(xiě))

用法:

int strcmp ( string $str1 , string $str2 )

8.strrev — 反轉(zhuǎn)字符串

用法:

string strrev ( string $string )

參考網(wǎng)站

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容