Ref/strings-Phpdoc专题
更多强大的字符串处理函数,参见 Perl 兼容正则表达式函数。 需要处理多字节字符集,参见 多字节字符函数。
addcslashes
以 C 语言风格使用反斜线转义字符串中的字符
说明
string <span
class="methodname">addcslashes ( <span
class="type">string $str , <span
class="methodparam">string $charlist
)
返回字符串,该字符串在属于参数 charlist 列表中的字符前都加上了反斜线。
参数
str
要转义的字符。
charlist
如果 charlist 中包含有 \n,\r 等字符,将以 C
语言风格转换,而其它非字母数字且 ASCII 码低于 32 以及高于 126
的字符均转换成使用八进制表示。
当定义 charlist 参数中的字符序列时,需要确实知道介于自己设置的开始及结束范围之内的都是些什么字符。
<?php
echo addcslashes('foo[ ]', 'A..z');
// 输出:\f\o\o\[ \]
// 所有大小写字母均被转义
// ... 但 [\]^_` 以及分隔符、换行符、回车符等也一并被转义了。
?>
另外,如果设置范围中的结束字符 ASCII 码高于开始字符,则不会创建范围,只是将开始字符、结束字符以及其间的字符逐个转义。可使用 ord 函数获取字符的 ASCII 码值。
<?php
echo addcslashes("zoo['.']", 'z..A');
// 输出:\zoo['\.']
?>
当选择对字符 0,a,b,f,n,r,t 和 v 进行转义时需要小心,它们将被转换成 \0,\a,\b,\f,\n,\r,\t 和 \v。在 PHP 中,只有 \0(NULL),\r(回车符),\n(换行符)和 \t(制表符)是预定义的转义序列, 而在 C 语言中,上述的所有转换后的字符都是预定义的转义序列。
返回值
返回转义后的字符。
更新日志
| 版本 | 说明 |
|---|---|
| 5.2.5 | The escape sequences \v and \f were added. |
范例
charlist 参数,如“\0..\37”,将转义所有 ASCII 码介于 0 和 31
之间的字符。
示例 #1 addcslashes 例子
<?php
$escaped = addcslashes($not_escaped, "\0..\37!@\177..\377");
?>
参见
- stripcslashes
- stripslashes
- addslashes
- htmlspecialchars
- quotemeta
addslashes
使用反斜线引用字符串
说明
string <span
class="methodname">addslashes ( <span
class="type">string $str )
返回字符串,该字符串为了数据库查询语句等的需要在某些字符前加上了反斜线。这些字符是单引号(')、双引号(")、反斜线(\)与
NUL(null 字符)。
一个使用 addslashes 的例子是当你要往数据库中输入数据时。 例如,将名字 O'reilly 插入到数据库中,这就需要对其进行转义。 强烈建议使用 DBMS 指定的转义函数 (比如 MySQL 是 <span class="function">mysqli_real_escape_string,PostgreSQL 是 pg_escape_string),但是如果你使用的 DBMS 没有一个转义函数,并且使用 \* 来转义特殊字符,你可以使用这个函数。 仅仅是为了获取插入数据库的数据,额外的 \ 并不会插入。 当 PHP 指令 magic_quotes_sybase 被设置成 on 时,意味着插入 ' 时将使用 '* 进行转义。
PHP 5.4 之前 PHP 指令 magic_quotes_gpc 默认是 on, 实际上所有的 GET、POST 和 COOKIE 数据都用被 <span class="function">addslashes 了。 不要对已经被 magic_quotes_gpc 转义过的字符串使用 <span class="function">addslashes,因为这样会导致双层转义。 遇到这种情况时可以使用函数 <span class="function">get_magic_quotes_gpc 进行检测。
参数
str
要转义的字符。
返回值
返回转义后的字符。
范例
示例 #1 一个 addslashes 例子
<?php
$str = "Is your name O'reilly?";
// 输出: Is your name O\'reilly?
echo addslashes($str);
?>
参见
- stripcslashes
- stripslashes
- addcslashes
- htmlspecialchars
- quotemeta
- get_magic_quotes_gpc
bin2hex
函数把包含数据的二进制字符串转换为十六进制值
说明
string bin2hex
( string
$str )
把二进制的参数 str
转换为的十六进制的字符串。转换使用字节方式,高四位字节优先。
参数
str
二进制字符串。
返回值
返回指定字符串十六进制的表示。
参见
- hex2bin
- pack
chop
rtrim 的别名
说明
此函数是该函数的别名:rtrim。
注释
Note:
chop 与 Perl 的 chop() 函数有所不同,它会删除字符串的最后一个字符。
chr
返回指定的字符
说明
string chr (
int $ascii
)
返回相对应于 ascii 所指定的单个字符。
此函数与 ord 是互补的。
参数
ascii
Ascii 码。
返回值
返回规定的字符。
范例
示例 #1 chr 例子
<?php
$str = "The string ends in escape: ";
$str .= chr(27); /* 在 $str 后边增加换码符 */
/* 通常这样更有用 */
$str = sprintf("The string ends in escape: %c", 27);
?>
参见
- sprintf 如何使用格式字符串 %c。
- ord
- 可以在此处找到 ASCII 码表:» http://www.asciitable.com。
chunk_split
将字符串分割成小块
说明
string <span
class="methodname">chunk_split ( <span
class="type">string $body [, <span
class="methodparam">int $chunklen<span
class="initializer"> = 76 [, <span
class="methodparam">string $end<span
class="initializer"> = "\r\n" ]] )
使用此函数将字符串分割成小块非常有用。例如将 <span
class="function">base64_encode 的输出转换成符合 RFC 2045
语义的字符串。它会在每 chunklen 个字符后边插入 end。
参数
body
要分割的字符。
chunklen
分割的尺寸。
end
行尾序列符号。
返回值
返回分割后的字符。
范例
示例 #1 chunk_split 例子
<?php
// 使用 RFC 2045 语义格式化 $data
$new_string = chunk_split(base64_encode($data));
?>
参见
- str_split
- explode
- split
- wordwrap
- » RFC 2045
convert_cyr_string
将字符由一种 Cyrillic 字符转换成另一种
说明
string <span
class="methodname">convert_cyr_string ( <span
class="methodparam">string $str ,
string
$from , <span
class="type">string $to )
此函数将给定的字符串从一种 Cyrillic 字符转换成另一种,返回转换之后的字符串。
参数
str
要转换的字符。
from
单个字符,代表源 Cyrillic 字符集。
to
单个字符,代表了目标 Cyrillic 字符集。
支持的类型有:
- k - koi8-r
- w - windows-1251
- i - iso8859-5
- a - x-cp866
- d - x-cp866
- m - x-mac-cyrillic
返回值
返回转换后的字符串。
注释
Note: 此函数可安全用于二进制对象。
convert_uudecode
解码一个 uuencode 编码的字符串
说明
string <span
class="methodname">convert_uudecode ( <span
class="methodparam">string $data )
convert_uudecode 解码一个 uuencode 编码的字符串。
参数
data
uuencode 编码后的数据
返回值
返回解码后的字符串数据, 或者在失败时返回 false.。
范例
示例 #1 convert_uudecode 例子
<?php
/* 你猜会输出啥?:) */
echo convert_uudecode("+22!L;W9E(%!(4\"$`\n`");
?>
参见
- convert_uuencode
convert_uuencode
使用 uuencode 编码一个字符串
说明
string <span
class="methodname">convert_uuencode ( <span
class="methodparam">string $data )
convert_uuencode 使用 uuencode 算法对一个字符串进行编码。
uuencode 算法会将所有(含二进制数据)字符串转化为可输出的字符, 并且可以被安全的应用于网络传输。使用 uuencode 编码后的数据 将会比源数据大35%左右
参数
data
需要被编码的数据。
返回值
返回 uuencode 编码后的数据 或者在失败时返回 false。
范例
示例 #1 convert_uuencode 例子
<?php
$some_string = "test\ntext text\r\n";
echo convert_uuencode($some_string);
?>
参见
- convert_uudecode
- base64_encode
count_chars
返回字符串所用字符的信息
说明
mixed <span
class="methodname">count_chars ( <span
class="type">string $string [, <span
class="methodparam">int $mode<span
class="initializer"> = 0 ] )
统计 string 中每个字节值(0..255)出现的次数,使用多种模式返回结果。
参数
string
需要统计的字符串。
mode
参见返回的值。
返回值
根据不同的 mode,count_chars
返回下列不同的结果:
- 0 - 以所有的每个字节值作为键名,出现次数作为值的数组。
- 1 - 与 0 相同,但只列出出现次数大于零的字节值。
- 2 - 与 0 相同,但只列出出现次数等于零的字节值。
- 3 - 返回由所有使用了的字节值组成的字符串。
- 4 - 返回由所有未使用的字节值组成的字符串。
范例
示例 #1 count_chars 示例
<?php
$data = "Two Ts and one F.";
foreach (count_chars($data, 1) as $i => $val) {
echo "There were $val instance(s) of \"" , chr($i) , "\" in the string.\n";
}
?>
以上例程会输出:
There were 4 instance(s) of " " in the string.
There were 1 instance(s) of "." in the string.
There were 1 instance(s) of "F" in the string.
There were 2 instance(s) of "T" in the string.
There were 1 instance(s) of "a" in the string.
There were 1 instance(s) of "d" in the string.
There were 1 instance(s) of "e" in the string.
There were 2 instance(s) of "n" in the string.
There were 2 instance(s) of "o" in the string.
There were 1 instance(s) of "s" in the string.
There were 1 instance(s) of "w" in the string.
参见
- strpos
- substr_count
crc32
计算一个字符串的 crc32 多项式
说明
int crc32 (
string $str
)
生成 str 的 32
位循环冗余校验码多项式。这通常用于检查传输的数据是否完整。
Warning
由于 PHP 的整数是带符号的,所以在 32 位系统上许多 crc32 校验码将返回负整数。 尽管在 64 位上所有 <span class="function">crc32 的结果将都是正整数。
因此你需要使用 sprintf 或 <span class="function">printf 的“%u”格式符来获取表示无符号 crc32 校验码的字符串。
For a hexadecimal representation of the checksum you can either use the "%x" formatter of sprintf or <span class="function">printf or the <span class="function">dechex conversion functions, both of these also take care of converting the crc32 result to an unsigned integer.
Having 64bit installations also return negative integers for higher result values was considered but would break the hexadecimal conversion as negatives would get an extra 0xFFFFFFFF######## offset then. As hexadecimal representation seems to be the most common use case we decided to not break this even if it breaks direct decimal comparisons in about 50% of the cases when moving from 32 to 64bits.
In retrospect having the function return an integer maybe wasn't the best idea and returning a hex string representation right away (as e.g. md5 does) might have been a better plan to begin with.
For a more portable solution you may also consider the generic <span
class="function">hash. hash("crc32b", $str) will return the
same string as dechex(crc32($str)).
参数
str
要校验的数据。
返回值
返回 str crc32 校验的整数。
范例
示例 #1 显示一个 crc32 校验码
示例中的第二行演示了如何使用 printf 函数转换校验码:
<?php
$checksum = crc32("The quick brown fox jumped over the lazy dog.");
printf("%u\n", $checksum);
?>
参见
- hash
- md5
- sha1
crypt
单向字符串散列
说明
string crypt (
string $str
[, string
$salt ] )
crypt 返回一个基于标准 UNIX DES 算法或系统上其他可用的替代算法的散列字符串。
salt 参数是可选的。然而,如果没有salt的话,<span
class="function">crypt创建出来的会是弱密码。 php
5.6及之后的版本会在没有它的情况下抛出一个 E_NOTICE
级别的错误。为了更好的安全性,请确保指定一个足够强度的盐值。
<span class="function">password_hash使用了一个强的哈希算法,来产生足够强的盐值,并且会自动进行合适的轮次。<span class="function">password_hash是<span class="function">crypt的一个简单封装,并且完全与现有的密码哈希兼容。推荐使用<span class="function">password_hash。
有些系统支持不止一种散列类型。实际上,有时候,基于 MD5
的算法被用来替代基于标准 DES 的算法。这种散列类型由盐值参数触发。在 5.3
之前,PHP 在安装时根据系统的 crypt()
决定可用的算法。如果没有提供盐值,PHP 将自动生成一个 2 个字符(DES)或者
12 个字符(MD5)的盐值 ,这取决于 MD5 crypt() 的可用性。PHP
设置了一个名为 CRYPT_SALT_LENGTH
的常量,用来表示可用散列允许的最长可用盐值。
基于标准 DES 算法的 crypt
在输出内容的开始位置返回两个字符的盐值。它也只使用 str 的开始 8
个字符,所以更长的以相同 8
个字符开始的字符串也将生成相同的结果(当使用了相同的盐值时)。
在 crypt() 函数支持多重散列的系统上,下面的常量根据相应的类型是否可用被设置为 0 或 1:
-
CRYPT_STD_DES- 基于标准 DES 算法的散列使用 "./0-9A-Za-z" 字符中的两个字符作为盐值。在盐值中使用非法的字符将导致 crypt() 失败。 -
CRYPT_EXT_DES- 扩展的基于 DES 算法的散列。其盐值为 9 个字符的字符串,由 1 个下划线后面跟着 4 字节循环次数和 4 字节盐值组成。它们被编码成可打印字符,每个字符 6 位,有效位最少的优先。0 到 63 被编码为 "./0-9A-Za-z"。在盐值中使用非法的字符将导致 crypt() 失败。 -
CRYPT_MD5- MD5 散列使用一个以 $1$ 开始的 12 字符的字符串盐值。 -
CRYPT_BLOWFISH- Blowfish 算法使用如下盐值:“$2a$”,一个两位 cost 参数,“$” 以及 64 位由 “./0-9A-Za-z” 中的字符组合而成的字符串。在盐值中使用此范围之外的字符将导致 crypt() 返回一个空字符串。两位 cost 参数是循环次数以 2 为底的对数,它的范围是 04-31,超出这个范围将导致 crypt() 失败。 PHP 5.3.7 之前只支持 “$2a$” 作为盐值的前缀,PHP 5.3.7 开始引入了新的前缀来修正一个在Blowfish实现上的安全风险。可以参考» this document来了解关于这个修复的更多信息。总而言之,开发者如果仅针对 PHP 5.3.7及之后版本进行开发,那应该使用 “$2y$” 而非 “$2a$” -
CRYPT_SHA256- SHA-256 算法使用一个以 $5$ 开头的 16 字符字符串盐值进行散列。如果盐值字符串以 “rounds=\<N>$” 开头,N 的数字值将被用来指定散列循环的执行次数,这点很像 Blowfish 算法的 cost 参数。默认的循环次数是 5000,最小是 1000,最大是 999,999,999。超出这个范围的 N 将会被转换为最接近的值。 -
CRYPT_SHA512- SHA-512 算法使用一个以 $6$ 开头的 16 字符字符串盐值进行散列。如果盐值字符串以 “rounds=\<N>$” 开头,N 的数字值将被用来指定散列循环的执行次数,这点很像 Blowfish 算法的 cost 参数。默认的循环次数是 5000,最小是 1000,最大是 999,999,999。超出这个范围的 N 将会被转换为最接近的值。
Note:
从 PHP 5.3.0 起,PHP 包含了它自己的实现,并将在系统缺乏相应算法支持的时候使用它自己的实现。
参数
str
待散列的字符串。
Caution
使用 CRYPT_BLOWFISH
算法将导致str被裁剪为一个最长72个字符的字符串。
salt
可选的盐值字符串。如果没有提供,算法行为将由不同的算法实现决定,并可能导致不可预料的结束。
返回值
返回散列后的字符串或一个少于 13 字符的字符串,从而保证在失败时与盐值区分开来。
Warning
当校验密码时,应该使用一个不容易被时间攻击的字符串比较函数来比较<span class="function">crypt的输出与之前已知的哈希。出于这个目的,PHP5.6开始提供了<span class="function">hash_equals。
更新日志
| 版本 | 说明 |
|---|---|
| 5.6.5 | When the failure string "*0" is given as the salt, "*1" will now be returned for consistency with other crypt implementations. Prior to this version, PHP 5.6 would incorrectly return a DES hash. |
| 5.6.0 | Raise E_NOTICE security warning if salt is omitted. |
| 5.5.21 | When the failure string "*0" is given as the salt, "*1" will now be returned for consistency with other crypt implementations. Prior to this version, PHP 5.5 (and earlier branches) would incorrectly return a DES hash. |
| 5.3.7 | Added $2x$ and $2y$ Blowfish modes to deal with potential high-bit attacks. |
| 5.3.2 | 基于 Ulrich Drepper 的» 实现,新增基于 SHA-256 算法和 SHA-512 算法的 crypt。 |
| 5.3.2 | 修正了 Blowfish 算法由于非法循环导致的问题,返回“失败”字符串(“*0” 或 “*1”)而不是转而使用 DES 算法。 |
| 5.3.0 | PHP 现在包含了它自己的 MD5 Crypt 实现,包括标准 DES 算法,扩展的 DES 算法以及 Blowfish 算法。如果系统缺乏相应的实现,那么 PHP 将使用它自己的实现。 |
范例
示例 #1 crypt 范例
<?php
$hashed_password = crypt('mypassword'); // 自动生成盐值
/* 你应当使用 crypt() 得到的完整结果作为盐值进行密码校验,以此来避免使用不同散列算法导致的问题。(如上所述,基于标准 DES 算法的密码散列使用 2 字符盐值,但是基于 MD5 算法的散列使用 12 个字符盐值。)*/
if (hash_equals($hashed_password, crypt($user_input, $hashed_password))) {
echo "Password verified!";
}
?>
示例 #2 利用 htpasswd 进行 crypt 加密
<?php
// 设置密码
$password = 'mypassword';
// 获取散列值,使用自动盐值
$hash = crypt($password);
?>
示例 #3 以不同散列类型使用 crypt
<?php
if (CRYPT_STD_DES == 1) {
echo 'Standard DES: ' . crypt('rasmuslerdorf', 'rl') . "\n";
}
if (CRYPT_EXT_DES == 1) {
echo 'Extended DES: ' . crypt('rasmuslerdorf', '_J9..rasm') . "\n";
}
if (CRYPT_MD5 == 1) {
echo 'MD5: ' . crypt('rasmuslerdorf', '$1$rasmusle$') . "\n";
}
if (CRYPT_BLOWFISH == 1) {
echo 'Blowfish: ' . crypt('rasmuslerdorf', '$2a$07$usesomesillystringforsalt$') . "\n";
}
if (CRYPT_SHA256 == 1) {
echo 'SHA-256: ' . crypt('rasmuslerdorf', '$5$rounds=5000$usesomesillystringforsalt$') . "\n";
}
if (CRYPT_SHA512 == 1) {
echo 'SHA-512: ' . crypt('rasmuslerdorf', '$6$rounds=5000$usesomesillystringforsalt$') . "\n";
}
?>
以上例程的输出类似于:
Standard DES: rl.3StKT.4T8M
Extended DES: _J9..rasmBYk8r9AiWNc
MD5: $1$rasmusle$rISCgZzpwk3UhDidwXvin0
Blowfish: $2a$07$usesomesillystringfore2uDLvp1Ii2e./U9C8sBjqp8I90dH6hi
SHA-256: $5$rounds=5000$usesomesillystri$KqJWpanXZHKq2BOB43TSaYhEWsQ1Lr5QNyPCDH/Tp.6
SHA-512: $6$rounds=5000$usesomesillystri$D4IrlXatmP7rx3P3InaxBeoomnAihCKRVQP22JZ6EY47Wc6BkroIuUUBOov1i.S5KPgErtP/EN5mcO.ChWQW21
注释
Note: 由于 <span class="function">crypt 使用的是单向算法,因此不存在 decrypt 函数。
参见
- hash_equals
- password_hash
- md5
- Mcrypt 扩展
- 更多关于 crypt 函数的信息,请阅读 Unix man 页面
echo
输出一个或多个字符串
说明
void echo (
string
$arg1 [, <span
class="type">string $... ] )
输出所有参数。不会换行。
echo 不是一个函数(它是一个语言结构), 因此你不一定要使用小括号来指明参数,单引号,双引号都可以。 <span class="function">echo (不像其他语言构造)不表现得像一个函数, 所以不能总是使用一个函数的上下文。 另外,如果你想给<span class="function">echo 传递多个参数, 那么就不能使用小括号。
echo 也有一个快捷用法,你可以在打开标记前直接用一个等号。在 PHP 5.4.0 之前,必须在php.ini 里面启用 short_open_tag 才有效。
I have <?=$foo?> foo.
和 print 最主要的不同之处是, echo 接受参数列表,并且没有返回值。
参数
arg1
要输出的参数
...
返回值
没有返回值。
范例
示例 #1 echo 例子
<?php
echo "Hello World";
// Strings can either be passed individually as multiple arguments or
// concatenated together and passed as a single argument
echo 'This ', 'string ', 'was ', 'made ', 'with multiple parameters.', chr(10);
echo 'This ' . 'string ' . 'was ' . 'made ' . 'with concatenation.' . "\n";
// Because echo does not behave like a function, the following code is invalid.
($some_var) ? echo 'true' : echo 'false';
// However, the following examples will work:
($some_var) ? print 'true' : print 'false'; // print is also a construct, but
// it behaves like a function, so
// it may be used in this context.
echo $some_var ? 'true': 'false'; // changing the statement around
?>
注释
Note: <span class="simpara">因为是一个语言构造器而不是一个函数,不能被 可变函数 调用。
小贴士
相对 echo 中拼接字符串而言,传递多个参数比较好,考虑到了 PHP 中连接运算符(“.”)的优先级。 传入多个参数,不需要圆括号保证优先级:
<?php
echo "Sum: ", 1 + 2;
echo "Hello ", isset($name) ? $name : "John Doe", "!";
如果拼接字符串,连接运算符(“.”)相对于加号优先级相同,比三元运算符优先级更高。为了正确,必须使用圆括号:
<?php
echo 'Sum: ' . (1 + 2);
echo 'Hello ' . (isset($name) ? $name : 'John Doe') . '!';
参见
- printf
- flush
- Heredoc 语法
explode
使用一个字符串分割另一个字符串
说明
array explode
( string
$delimiter , <span
class="type">string $string [, <span
class="methodparam">int $limit ] )
此函数返回由字符串组成的数组,每个元素都是 string
的一个子串,它们被字符串 delimiter 作为边界点分割出来。
参数
delimiter
边界上的分隔字符。
string
输入的字符串。
limit
如果设置了 limit 参数并且是正数,则返回的数组包含最多 limit
个元素,而最后那个元素将包含 string 的剩余部分。
如果 limit 参数是负数,则返回除了最后的 -limit 个元素外的所有元素。
如果 limit 是 0,则会被当做 1。
由于历史原因,虽然 implode
可以接收两种参数顺序,但是 explode
不行。你必须保证 separator 参数在 string 参数之前才行。
返回值
此函数返回由字符串组成的 array,每个元素都是
string 的一个子串,它们被字符串 delimiter 作为边界点分割出来。
如果 delimiter 为空字符串(""),explode
将返回 false。 如果 delimiter 所包含的值在 string
中找不到,并且使用了负数的 limit , 那么会返回空的 <span
class="type">array, 否则返回包含 string 单个元素的数组。
更新日志
| 版本 | 说明 |
|---|---|
| 5.1.0 | 支持负数的 limit |
| 4.0.1 | 增加了参数 limit |
范例
示例 #1 explode 例子
<?php
// 示例 1
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
// 示例 2
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
echo $user; // foo
echo $pass; // *
?>
示例 #2 explode return examples
<?php
/* A string that doesn't contain the delimiter will simply return a one-length array of the original string. */
$input1 = "hello";
$input2 = "hello,there";
var_dump( explode( ',', $input1 ) );
var_dump( explode( ',', $input2 ) );
?>
以上例程会输出:
array(1)
(
[0] => string(5) "hello"
)
array(2)
(
[0] => string(5) "hello"
[1] => string(5) "there"
)
示例 #3 limit 参数的例子
<?php
$str = 'one|two|three|four';
// 正数的 limit
print_r(explode('|', $str, 2));
// 负数的 limit(自 PHP 5.1 起)
print_r(explode('|', $str, -1));
?>
以上例程会输出:
Array
(
[0] => one
[1] => two|three|four
)
Array
(
[0] => one
[1] => two
[2] => three
)
注释
Note: 此函数可安全用于二进制对象。
参见
- preg_split
- str_split
- mb_split
- str_word_count
- strtok
- implode
fprintf
将格式化后的字符串写入到流
说明
int fprintf (
resource
$handle , <span
class="type">string $format [, <span
class="methodparam">mixed $... ] )
写入一个根据 format 格式化后的字符串到 由 handle 句柄打开的流中。
参数
handle
文件系统指针,是典型地由 fopen 创建的
resource(资源)。
format
The format string is composed of zero or more directives: ordinary
characters (excluding %) that are copied directly to the result and
conversion specifications, each of which results in fetching its own
parameter.
A conversion specification follows this prototype: %[argnum$][flags][width][.precision]specifier.
Argnum
An integer followed by a dollar sign $, to specify which number argument to treat in the conversion.
| Flag | 说明 |
|---|---|
| - | Left-justify within the given field width; Right justification is the default |
| + | Prefix positive numbers with a plus sign +; Default only negative are prefixed with a negative sign. |
| (space) | Pads the result with spaces. This is the default. |
| 0 | Only left-pads numbers with zeros. With s specifiers this can also right-pad with zeros. |
| '(char) | Pads the result with the character (char). |
Width
An integer that says how many characters (minimum) this conversion should result in.
Precision
A period . followed by an integer who's meaning depends on the specifier:
- For e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6).
- For g and G specifiers: this is the maximum number of significant digits to be printed.
- For s specifier: it acts as a cutoff point, setting a maximum character limit to the string.
Note: If the period is specified without an explicit value for precision, 0 is assumed.
Note: Attempting to use a position specifier greater than
PHP_INT_MAXwill generate warnings.
| Specifier | 说明 |
|---|---|
| % | A literal percent character. No argument is required. |
| b | The argument is treated as an integer and presented as a binary number. |
| c | The argument is treated as an integer and presented as the character with that ASCII. |
| d | The argument is treated as an integer and presented as a (signed) decimal number. |
| e | The argument is treated as scientific notation (e.g. 1.2e+2). The precision specifier stands for the number of digits after the decimal point since PHP 5.2.1. In earlier versions, it was taken as number of significant digits (one less). |
| E | Like the e specifier but uses uppercase letter (e.g. 1.2E+2). |
| f | The argument is treated as a float and presented as a floating-point number (locale aware). |
| F | The argument is treated as a float and presented as a floating-point number (non-locale aware). Available as of PHP 5.0.3. |
| g | General format. Let P equal the precision if nonzero, 6 if the precision is omitted, or 1 if the precision is zero. Then, if a conversion with style E would have an exponent of X: If P > X ≥ −4, the conversion is with style f and precision P − (X + 1). Otherwise, the conversion is with style e and precision P − 1. |
| G | Like the g specifier but uses E and f. |
| o | The argument is treated as an integer and presented as an octal number. |
| s | The argument is treated and presented as a string. |
| u | The argument is treated as an integer and presented as an unsigned decimal number. |
| x | The argument is treated as an integer and presented as a hexadecimal number (with lowercase letters). |
| X | The argument is treated as an integer and presented as a hexadecimal number (with uppercase letters). |
Warning The c type specifier ignores padding and width
Warning Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results
Variables will be co-erced to a suitable type for the specifier:
| Type | Specifiers |
|---|---|
| string | s |
| integer | d, u, c, o, x, X, b |
| double | g, G, e, E, f, F |
...
返回值
返回写入的字符串长度。
范例
示例 #1 fprintf: zero-padded integers
<?php
if (!($fp = fopen('date.txt', 'w'))) {
return;
}
fprintf($fp, "%04d-%02d-%02d", $year, $month, $day);
// will write the formatted ISO date to date.txt
?>
示例 #2 fprintf: formatting currency
<?php
if (!($fp = fopen('currency.txt', 'w'))) {
return;
}
$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;
// echo $money will output "123.1";
$len = fprintf($fp, '%01.2f', $money);
// will write "123.10" to currency.txt
echo "wrote $len bytes to currency.txt";
// use the return value of fprintf to determine how many bytes we wrote
?>
参见
- printf
- sprintf
- vprintf
- vsprintf
- vfprintf
- sscanf
- fscanf
- number_format
- date
get_html_translation_table
返回使用 htmlspecialchars 和 <span class="function">htmlentities 后的转换表
说明
array <span
class="methodname">get_html_translation_table ([ <span
class="methodparam">int $table<span
class="initializer"> = HTML_SPECIALCHARS [, <span
class="methodparam">int $flags<span
class="initializer"> = ENT_COMPAT | ENT_HTML401 [,
string
$encoding = 'UTF-8' ]]] )
get_html_translation_table 将返回 <span class="function">htmlspecialchars 和 <span class="function">htmlentities 处理后的转换表。
Note:
特殊字符可以使用多种转换方式。 例如: " 可以被转换成 ", " 或者 ". <span class="function">get_html_translation_table 返回其中最常用的。
参数
table
有两个新的常量 (HTML_ENTITIES, HTML_SPECIALCHARS)
允许你指定你想要的表。
flags
A bitmask of one or more of the following flags, which specify which
quotes the table will contain as well as which document type the table
is for. The default is ENT_COMPAT | ENT_HTML401.
| Constant Name | Description |
|---|---|
ENT_COMPAT |
Table will contain entities for double-quotes, but not for single-quotes. |
ENT_QUOTES |
Table will contain entities for both double and single quotes. |
ENT_NOQUOTES |
Table will neither contain entities for single quotes nor for double quotes. |
ENT_HTML401 |
Table for HTML 4.01. |
ENT_XML1 |
Table for XML 1. |
ENT_XHTML |
Table for XHTML. |
ENT_HTML5 |
Table for HTML 5. |
encoding
Encoding to use. If omitted, the default value for this argument is
ISO-8859-1 in versions of PHP prior to 5.4.0, and UTF-8 from PHP 5.4.0
onwards.
支持以下字符集:
| 字符集 | 别名 | 描述 |
|---|---|---|
| ISO-8859-1 | ISO8859-1 | 西欧,Latin-1 |
| ISO-8859-5 | ISO8859-5 | Little used cyrillic charset (Latin/Cyrillic). |
| ISO-8859-15 | ISO8859-15 | 西欧,Latin-9。增加欧元符号,法语和芬兰语字母在 Latin-1(ISO-8859-1) 中缺失。 |
| UTF-8 | ASCII 兼容的多字节 8 位 Unicode。 | |
| cp866 | ibm866, 866 | DOS 特有的西里尔编码。本字符集在 4.3.2 版本中得到支持。 |
| cp1251 | Windows-1251, win-1251, 1251 | Windows 特有的西里尔编码。本字符集在 4.3.2 版本中得到支持。 |
| cp1252 | Windows-1252, 1252 | Windows 特有的西欧编码。 |
| KOI8-R | koi8-ru, koi8r | 俄语。本字符集在 4.3.2 版本中得到支持。 |
| BIG5 | 950 | 繁体中文,主要用于中国台湾省。 |
| GB2312 | 936 | 简体中文,中国国家标准字符集。 |
| BIG5-HKSCS | 繁体中文,附带香港扩展的 Big5 字符集。 | |
| Shift_JIS | SJIS, 932 | 日语 |
| EUC-JP | EUCJP | 日语 |
| MacRoman | Mac OS 使用的字符串。 | |
| '' | An empty string activates detection from script encoding (Zend multibyte), default_charset and current locale (see nl_langinfo and setlocale), in this order. Not recommended. |
Note: 其他字符集没有认可。将会使用默认编码并抛出异常。
返回值
将转换表作为一个数组返回。
更新日志
| 版本 | 说明 |
|---|---|
| 5.4.0 | The default value for the encoding parameter was changed to UTF-8. |
| 5.4.0 | The constants ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added. |
| 5.3.4 | The encoding parameter was added. |
范例
示例 #1 Translation Table Example
<?php
var_dump(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES | ENT_HTML5));
?>
以上例程的输出类似于:
array(1510) {
["
"]=>
string(9) "
"
["!"]=>
string(6) "!"
["""]=>
string(6) """
["#"]=>
string(5) "#"
["$"]=>
string(8) "$"
["%"]=>
string(8) "%"
["&"]=>
string(5) "&"
["'"]=>
string(6) "'"
// ...
}
参见
- htmlspecialchars
- htmlentities
- html_entity_decode
hebrev
将逻辑顺序希伯来文(logical-Hebrew)转换为视觉顺序希伯来文(visual-Hebrew)
说明
string hebrev
( string
$hebrew_text [, <span
class="type">int $max_chars_per_line
= 0 ] )
将逻辑顺序希伯来文(logical-Hebrew)转换为视觉顺序希伯来文(visual-Hebrew)
函数将会尝试避免破坏单词。
参数
hebrew_text
逻辑顺序希伯来文字符串。
max_chars_per_line
可选参数,表示每行可返回的最多字符数。
返回值
返回视觉顺序字符串。
参见
- hebrevc
hebrevc
将逻辑顺序希伯来文(logical-Hebrew)转换为视觉顺序希伯来文(visual-Hebrew),并且转换换行符
说明
string hebrevc
( string
$hebrew_text [, <span
class="type">int $max_chars_per_line
= 0 ] )
本函数与hebrev 一样,唯一的区别是 本函数会额外将换行符(\n)转换为"\<br>\n"。
函数将会尝试避免破坏单词。
参数
hebrew_text
逻辑顺序希伯来文字符串。
max_chars_per_line
可选参数,表示每行可返回的最多字符数。
返回值
返回视觉顺序字符串。
参见
- hebrev
hex2bin
转换十六进制字符串为二进制字符串
说明
string hex2bin
( string
$data )
转换十六进制字符串为二进制字符串。
Caution
这个函数不是 转换十六进制数字为二进制数字。这种转换可以使用<span class="function">base_convert 函数。
参数
data
十六进制表示的数据
返回值
返回给定数据的二进制表示 或者在失败时返回 false。
错误/异常
如果输入的十六进制字符串是奇数长数或者无效的十六进制字符串将会抛出
E_WARNING 级别的错误。
更新日志
| 版本 | 说明 |
|---|---|
| 5.5.1 | 如果输入的字符串是无效的十六进制字符串则抛出一个警告, |
| 5.4.4 | 如果输入的字符串有多余将抛出异常。 PHP 5.4.0 起字符串将被静默地接受,但是最后的字节会被截断。 |
范例
示例 #1 hex2bin 例子
<?php
$hex = hex2bin("6578616d706c65206865782064617461");
var_dump($hex);
?>
以上例程的输出类似于:
string(16) "example hex data"
参见
- bin2hex
- unpack
html_entity_decode
Convert HTML entities to their corresponding characters
说明
string <span
class="methodname">html_entity_decode ( <span
class="methodparam">string $string
[, int
$flags = ENT_COMPAT [,
<span
class="type">stringnull
$encoding = null ]] )
html_entity_decode is the opposite of
htmlentities in that it converts HTML
entities in the string to their corresponding characters.
More precisely, this function decodes all the entities (including all numeric entities) that a) are necessarily valid for the chosen document type — i.e., for XML, this function does not decode named entities that might be defined in some DTD — and b) whose character or characters are in the coded character set associated with the chosen encoding and are permitted in the chosen document type. All other entities are left as is.
参数
string
The input string.
flags
A bitmask of one or more of the following flags, which specify how to
handle quotes and which document type to use. The default is
ENT_COMPAT | ENT_HTML401.
| Constant Name | Description |
|---|---|
ENT_COMPAT |
Will convert double-quotes and leave single-quotes alone. |
ENT_QUOTES |
Will convert both double and single quotes. |
ENT_NOQUOTES |
Will leave both double and single quotes unconverted. |
ENT_HTML401 |
Handle code as HTML 4.01. |
ENT_XML1 |
Handle code as XML 1. |
ENT_XHTML |
Handle code as XHTML. |
ENT_HTML5 |
Handle code as HTML 5. |
encoding
An optional argument defining the encoding used when converting
characters.
If omitted, the default value of the encoding varies depending on the
PHP version in use. In PHP 5.6 and later, the
default_charset
configuration option is used as the default value. PHP 5.4 and 5.5 will
use UTF-8 as the default. Earlier versions of PHP use ISO-8859-1.
Although this argument is technically optional, you are highly encouraged to specify the correct value for your code if you are using PHP 5.5 or earlier, or if your default_charset configuration option may be set incorrectly for the given input.
支持以下字符集:
| 字符集 | 别名 | 描述 |
|---|---|---|
| ISO-8859-1 | ISO8859-1 | 西欧,Latin-1 |
| ISO-8859-5 | ISO8859-5 | Little used cyrillic charset (Latin/Cyrillic). |
| ISO-8859-15 | ISO8859-15 | 西欧,Latin-9。增加欧元符号,法语和芬兰语字母在 Latin-1(ISO-8859-1) 中缺失。 |
| UTF-8 | ASCII 兼容的多字节 8 位 Unicode。 | |
| cp866 | ibm866, 866 | DOS 特有的西里尔编码。本字符集在 4.3.2 版本中得到支持。 |
| cp1251 | Windows-1251, win-1251, 1251 | Windows 特有的西里尔编码。本字符集在 4.3.2 版本中得到支持。 |
| cp1252 | Windows-1252, 1252 | Windows 特有的西欧编码。 |
| KOI8-R | koi8-ru, koi8r | 俄语。本字符集在 4.3.2 版本中得到支持。 |
| BIG5 | 950 | 繁体中文,主要用于中国台湾省。 |
| GB2312 | 936 | 简体中文,中国国家标准字符集。 |
| BIG5-HKSCS | 繁体中文,附带香港扩展的 Big5 字符集。 | |
| Shift_JIS | SJIS, 932 | 日语 |
| EUC-JP | EUCJP | 日语 |
| MacRoman | Mac OS 使用的字符串。 | |
| '' | An empty string activates detection from script encoding (Zend multibyte), default_charset and current locale (see nl_langinfo and setlocale), in this order. Not recommended. |
Note: 其他字符集没有认可。将会使用默认编码并抛出异常。
返回值
Returns the decoded string.
更新日志
| 版本 | 说明 |
|---|---|
| 8.0.0 | encoding is nullable now. |
范例
示例 #1 Decoding HTML entities
<?php
$orig = "I'll \"walk\" the <b>dog</b> now";
$a = htmlentities($orig);
$b = html_entity_decode($a);
echo $a; // I'll "walk" the <b>dog</b> now
echo $b; // I'll "walk" the <b>dog</b> now
?>
注释
Note:
You might wonder why trim(html_entity_decode(' ')); doesn't reduce the string to an empty string, that's because the ' ' entity is not ASCII code 32 (which is stripped by <span class="function">trim) but ASCII code 160 (0xa0) in the default ISO 8859-1 encoding.
参见
- htmlentities
- htmlspecialchars
- get_html_translation_table
- urldecode
htmlentities
将字符转换为 HTML 转义字符
说明
string <span
class="methodname">htmlentities ( <span
class="type">string $string [, <span
class="methodparam">int $flags<span
class="initializer"> = ENT_COMPAT | ENT_HTML401 [,
string
$encoding =
ini_get("default_charset") [, <span
class="methodparam">bool $double_encode<span
class="initializer"> = true ]]] )
本函数各方面都和 htmlspecialchars 一样, 除了 htmlentities 会转换所有具有 HTML 实体的字符。
如果要解码(反向操作),可以使用 <span class="function">html_entity_decode。
参数
string
输入字符。
flags
以下一组位掩码标记,用于设置如何处理引号、无效代码序列、使用文档的类型。
默认是 ENT_COMPAT | ENT_HTML401。
| 常量名 | 描述 |
|---|---|
ENT_COMPAT |
会转换双引号,不转换单引号。 |
ENT_QUOTES |
既转换双引号也转换单引号。 |
ENT_NOQUOTES |
单/双引号都不转换 |
ENT_IGNORE |
静默丢弃无效的代码单元序列,而不是返回空字符串。 不建议使用此标记, 因为它» 可能有安全影响。 |
ENT_SUBSTITUTE |
替换无效的代码单元序列为 Unicode 代替符(Replacement Character), U+FFFD (UTF-8) 或者 � (其他),而不是返回空字符串。 |
ENT_DISALLOWED |
为文档的无效代码点替换为 Unicode 代替符(Replacement Character): U+FFFD (UTF-8),或 �(其他),而不是把它们留在原处。 比如以下情况下就很有用:要保证 XML 文档嵌入额外内容时格式合法。 |
ENT_HTML401 |
以 HTML 4.01 处理代码。 |
ENT_XML1 |
以 XML 1 处理代码。 |
ENT_XHTML |
以 XHTML 处理代码。 |
ENT_HTML5 |
以 HTML 5 处理代码。 |
encoding
An optional argument defining the encoding used when converting
characters.
If omitted, the default value of the encoding varies depending on the
PHP version in use. In PHP 5.6 and later, the
default_charset
configuration option is used as the default value. PHP 5.4 and 5.5 will
use UTF-8 as the default. Earlier versions of PHP use ISO-8859-1.
Although this argument is technically optional, you are highly encouraged to specify the correct value for your code if you are using PHP 5.5 or earlier, or if your default_charset configuration option may be set incorrectly for the given input.
支持以下字符集:
| 字符集 | 别名 | 描述 |
|---|---|---|
| ISO-8859-1 | ISO8859-1 | 西欧,Latin-1 |
| ISO-8859-5 | ISO8859-5 | Little used cyrillic charset (Latin/Cyrillic). |
| ISO-8859-15 | ISO8859-15 | 西欧,Latin-9。增加欧元符号,法语和芬兰语字母在 Latin-1(ISO-8859-1) 中缺失。 |
| UTF-8 | ASCII 兼容的多字节 8 位 Unicode。 | |
| cp866 | ibm866, 866 | DOS 特有的西里尔编码。本字符集在 4.3.2 版本中得到支持。 |
| cp1251 | Windows-1251, win-1251, 1251 | Windows 特有的西里尔编码。本字符集在 4.3.2 版本中得到支持。 |
| cp1252 | Windows-1252, 1252 | Windows 特有的西欧编码。 |
| KOI8-R | koi8-ru, koi8r | 俄语。本字符集在 4.3.2 版本中得到支持。 |
| BIG5 | 950 | 繁体中文,主要用于中国台湾省。 |
| GB2312 | 936 | 简体中文,中国国家标准字符集。 |
| BIG5-HKSCS | 繁体中文,附带香港扩展的 Big5 字符集。 | |
| Shift_JIS | SJIS, 932 | 日语 |
| EUC-JP | EUCJP | 日语 |
| MacRoman | Mac OS 使用的字符串。 | |
| '' | An empty string activates detection from script encoding (Zend multibyte), default_charset and current locale (see nl_langinfo and setlocale), in this order. Not recommended. |
Note: 其他字符集没有认可。将会使用默认编码并抛出异常。
double_encode
关闭 double_encode 时,PHP 不会转换现有的 HTML 实体, 默认是全部转换。
返回值
返回编码后的字符。
如果指定的编码 encoding 里, string 包含了无效的代码单元序列,
没有设置 ENT_IGNORE 或者 ENT_SUBSTITUTE
标记的情况下,会返回空字符串。
更新日志
| 版本 | 说明 |
|---|---|
| 5.6.0 | The default value for the encoding parameter was changed to be the value of the default_charset configuration option. |
| 5.4.0 | encoding 参数的默认值改成 UTF-8。 |
| 5.4.0 | 增加常量 ENT_SUBSTITUTE、 ENT_DISALLOWED、 ENT_HTML401、 ENT_XML1、 ENT_XHTML、 ENT_HTML5。 |
| 5.3.0 | 增加常量 ENT_IGNORE。 |
| 5.2.3 | 增加参数 double_encode。 |
范例
示例 #1 htmlentities 例子
<?php
$str = "A 'quote' is <b>bold</b>";
// 输出: A 'quote' is <b>bold</b>
echo htmlentities($str);
// 输出: A 'quote' is <b>bold</b>
echo htmlentities($str, ENT_QUOTES);
?>
示例 #2 ENT_IGNORE 用法示例
<?php
$str = "\x8F!!!";
// 输出空 string
echo htmlentities($str, ENT_QUOTES, "UTF-8");
// 输出 "!!!"
echo htmlentities($str, ENT_QUOTES | ENT_IGNORE, "UTF-8");
?>
参见
- html_entity_decode
- get_html_translation_table
- htmlspecialchars
- nl2br
- urlencode
htmlspecialchars_decode
将特殊的 HTML 实体转换回普通字符
说明
string <span
class="methodname">htmlspecialchars_decode ( <span
class="methodparam">string $string
[, int
$flags = ENT_COMPAT |
ENT_HTML401 ] )
此函数的作用和 htmlspecialchars 刚好相反。它将特殊的HTML实体转换回普通字符。
被转换的实体有: &, " (没有设置ENT_NOQUOTES 时),
' (设置了 ENT_QUOTES 时), < 以及>。
参数
string
要解码的字符串
flags
用下列标记中的一个或多个作为一个位掩码,来指定如何处理引号和使用哪种文档类型。默认为
ENT_COMPAT | ENT_HTML401。
| 常量名 | 说明 |
|---|---|
ENT_COMPAT |
转换双引号,不转换单引号。 |
ENT_QUOTES |
单引号和双引号都转换。 |
ENT_NOQUOTES |
单引号和双引号都不转换。 |
ENT_HTML401 |
作为HTML 4.01编码处理。 |
ENT_XML1 |
作为XML 1编码处理。 |
ENT_XHTML |
作为XHTML编码处理。 |
ENT_HTML5 |
作为HTML 5编码处理。 |
返回值
返回解码后的字符串。
更新日志
| 版本 | 说明 |
|---|---|
| 5.4.0 | 增加了 ENT_HTML401、ENT_XML1、 ENT_XHTML 和 ENT_HTML5 等常量。 |
范例
示例 #1 一个 htmlspecialchars_decode 的例子
<?php
$str = "<p>this -> "</p>\n";
echo htmlspecialchars_decode($str);
// 注意,这里的引号不会被转换
echo htmlspecialchars_decode($str, ENT_NOQUOTES);
?>
以上例程会输出:
<p>this -> "</p>
<p>this -> "</p>
参见
- htmlspecialchars
- html_entity_decode
- get_html_translation_table
htmlspecialchars
将特殊字符转换为 HTML 实体
说明
string <span
class="methodname">htmlspecialchars ( <span
class="methodparam">string $string
[, int
$flags = ENT_COMPAT |
ENT_HTML401 [, <span
class="type">string $encoding =
ini_get("default_charset") [, <span
class="methodparam">bool $double_encode<span
class="initializer"> = true ]]] )
某类字符在 HTML 中有特殊用处,如需保持原意,需要用 HTML 实体来表达。 本函数会返回字符转义后的表达。 如需转换子字符串中所有关联的名称实体,使用 <span class="function">htmlentities 代替本函数。
如果传入字符的字符编码和最终的文档是一致的,则用函数处理的输入适合绝大多数 HTML 文档环境。 然而,如果输入的字符编码和最终包含字符的文档是不一样的, 想要保留字符(以数字或名称实体的形式),本函数以及 <span class="function">htmlentities (仅编码名称实体对应的子字符串)可能不够用。 这种情况可以使用 <span class="function">mb_encode_numericentity 代替。
| 字符 | 替换后 |
|---|---|
| & (& 符号) | & |
| " (双引号) | ",除非设置了 ENT_NOQUOTES |
| ' (单引号) | 设置了 ENT_QUOTES 后, ' (如果是 ENT_HTML401) ,或者 ' (如果是 ENT_XML1、 ENT_XHTML 或 ENT_HTML5)。 |
| \< (小于) | < |
| > (大于) | > |
参数
string
待转换的 string。
flags
位掩码,由以下某个或多个标记组成,设置转义处理细节、无效单元序列、文档类型。
默认是 ENT_COMPAT | ENT_HTML401。
| 常量名称 | 描述 |
|---|---|
ENT_COMPAT |
会转换双引号,不转换单引号。 |
ENT_QUOTES |
既转换双引号也转换单引号。 |
ENT_NOQUOTES |
单/双引号都不转换 |
ENT_IGNORE |
静默丢弃无效的代码单元序列,而不是返回空字符串。 不建议使用此标记, 因为它» 可能有安全影响。 |
ENT_SUBSTITUTE |
替换无效的代码单元序列为 Unicode 代替符(Replacement Character), U+FFFD (UTF-8) 或者 � (其他),而不是返回空字符串。 |
ENT_DISALLOWED |
为文档的无效代码点替换为 Unicode 代替符(Replacement Character): U+FFFD (UTF-8),或 �(其他),而不是把它们留在原处。 比如以下情况下就很有用:要保证 XML 文档嵌入额外内容时格式合法。 |
ENT_HTML401 |
以 HTML 4.01 处理代码。 |
ENT_XML1 |
以 XML 1 处理代码。 |
ENT_XHTML |
以 XHTML 处理代码。 |
ENT_HTML5 |
以 HTML 5 处理代码。 |
encoding
An optional argument defining the encoding used when converting
characters.
If omitted, the default value of the encoding varies depending on the
PHP version in use. In PHP 5.6 and later, the
default_charset
configuration option is used as the default value. PHP 5.4 and 5.5 will
use UTF-8 as the default. Earlier versions of PHP use ISO-8859-1.
Although this argument is technically optional, you are highly encouraged to specify the correct value for your code if you are using PHP 5.5 or earlier, or if your default_charset configuration option may be set incorrectly for the given input.
本函数使用效果上,如果 string 对以下字符编码是有效的, ISO-8859-1、
ISO-8859-15、 UTF-8、 cp866、 cp1251、 cp1252、 KOI8-R
将具有相同的效果。 也就是说,在这些编码里, 受 <span
class="function">htmlspecialchars 影响的字符会占据相同的位置。
支持以下字符集:
| 字符集 | 别名 | 描述 |
|---|---|---|
| ISO-8859-1 | ISO8859-1 | 西欧,Latin-1 |
| ISO-8859-5 | ISO8859-5 | Little used cyrillic charset (Latin/Cyrillic). |
| ISO-8859-15 | ISO8859-15 | 西欧,Latin-9。增加欧元符号,法语和芬兰语字母在 Latin-1(ISO-8859-1) 中缺失。 |
| UTF-8 | ASCII 兼容的多字节 8 位 Unicode。 | |
| cp866 | ibm866, 866 | DOS 特有的西里尔编码。本字符集在 4.3.2 版本中得到支持。 |
| cp1251 | Windows-1251, win-1251, 1251 | Windows 特有的西里尔编码。本字符集在 4.3.2 版本中得到支持。 |
| cp1252 | Windows-1252, 1252 | Windows 特有的西欧编码。 |
| KOI8-R | koi8-ru, koi8r | 俄语。本字符集在 4.3.2 版本中得到支持。 |
| BIG5 | 950 | 繁体中文,主要用于中国台湾省。 |
| GB2312 | 936 | 简体中文,中国国家标准字符集。 |
| BIG5-HKSCS | 繁体中文,附带香港扩展的 Big5 字符集。 | |
| Shift_JIS | SJIS, 932 | 日语 |
| EUC-JP | EUCJP | 日语 |
| MacRoman | Mac OS 使用的字符串。 | |
| '' | An empty string activates detection from script encoding (Zend multibyte), default_charset and current locale (see nl_langinfo and setlocale), in this order. Not recommended. |
Note: 其他字符集没有认可。将会使用默认编码并抛出异常。
double_encode
关闭 double_encode 时,PHP 不会转换现有的 HTML 实体, 默认是全部转换。
返回值
转换后的 string。
如果指定的编码 encoding 里, string 包含了无效的代码单元序列,
没有设置 ENT_IGNORE 或者 ENT_SUBSTITUTE
标记的情况下,会返回空字符串。
更新日志
| 版本 | 说明 |
|---|---|
| 5.6.0 | The default value for the encoding parameter was changed to be the value of the default_charset configuration option. |
| 5.4.0 | encoding 参数的默认值改成 UTF-8。 |
| 5.4.0 | 增加常量 ENT_SUBSTITUTE、 ENT_DISALLOWED、 ENT_HTML401、 ENT_XML1、 ENT_XHTML、 ENT_HTML5。 |
| 5.3.0 | 增加常量 ENT_IGNORE。 |
| 5.2.3 | 增加参数 double_encode。 |
范例
示例 #1 htmlspecialchars 例子
<?php
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new; // <a href='test'>Test</a>
?>
注释
Note:
注意,本函数不会转换以上列表以外的实体。 完整转换请参见 <span class="function">htmlentities。
Note:
如果
flags的设置模糊易混淆,将遵循以下规则:
- 当
ENT_COMPAT、ENT_QUOTES、ENT_NOQUOTES都没设置, 默认就是ENT_NOQUOTES。- 如果设置不止一个
ENT_COMPAT、ENT_QUOTES、ENT_NOQUOTES,优先级最高的是ENT_QUOTES, 其次是ENT_COMPAT。- 当
ENT_HTML401、ENT_HTML5、ENT_XHTML、ENT_XML1都没设置,默认是ENT_HTML401。- 如果设置不止一个
ENT_HTML401、ENT_HTML5、ENT_XHTML、ENT_XML1, 优先级最高的是ENT_HTML5其次是ENT_XHTML、ENT_XML1和ENT_HTML401。- 如果设置不止一个
ENT_DISALLOWED、ENT_IGNORE、ENT_SUBSTITUTE,优先级最高的是ENT_IGNORE, 其次是ENT_SUBSTITUTE。
参见
- get_html_translation_table
- htmlspecialchars_decode
- strip_tags
- htmlentities
- nl2br
implode
将一个一维数组的值转化为字符串
说明
string implode
( string
$glue , <span
class="type">array $pieces )
string implode
( array
$pieces )
用 glue 将一维数组的值连接为一个字符串。
Note:
因为历史原因,implode 可以接收两种参数顺序,但是为了和 explode 内的顺序保持一致,不按文档的方式已被废弃。
参数
glue
默认为空的字符串。
pieces
你想要转换的数组。
返回值
返回一个字符串,其内容为由 glue 分割开的数组的值。
更新日志
| 版本 | 说明 |
|---|---|
| 7.4.0 | 把参数 glue 放到 pieces 的后面已被废弃(就是不按文档中的顺序传递参数)。 |
范例
示例 #1 implode 例子
<?php
$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
echo $comma_separated; // lastname,email,phone
// Empty string when using an empty array:
var_dump(implode('hello', array())); // string(0) ""
?>
注释
Note: 此函数可安全用于二进制对象。
参见
- explode
- preg_split
- http_build_query
join
别名 implode
说明
此函数是该函数的别名: implode.
lcfirst
使一个字符串的第一个字符小写
说明
string lcfirst
( string
$str )
返回第一个字母小写的 str ,如果是字母的话。
需要注意的是“字母”是由当前语言区域决定的。比如,在默认的“C”区域像日耳曼语系中的元音变音a (ä) 将不会被转换。
参数
str
输入的字符串。
返回值
返回转换后的字符串。
范例
示例 #1 lcfirst 例子:
<?php
$foo = 'HelloWorld';
$foo = lcfirst($foo); // helloWorld
$bar = 'HELLO WORLD!';
$bar = lcfirst($bar); // hELLO WORLD!
$bar = lcfirst(strtoupper($bar)); // hELLO WORLD!
?>
参见
- ucfirst
- strtolower
- strtoupper
- ucwords
levenshtein
计算两个字符串之间的编辑距离
说明
int <span
class="methodname">levenshtein ( <span
class="type">string $str1 , <span
class="methodparam">string $str2 )
int <span
class="methodname">levenshtein ( <span
class="type">string $str1 , <span
class="methodparam">string $str2 ,
int
$cost_ins , <span
class="type">int $cost_rep , <span
class="methodparam">int $cost_del )
编辑距离,是指两个字串之间,通过替换、插入、删除等操作将字符串str1转换成str2所需要操作的最少字符数量。
该算法的复杂度是 O(m*n),其中 n 和 m 分别是str1 和str2的长度
(当和算法复杂度为O(max(n,m)**3)的<span
class="function">similar_text相比时,此函数还是相当不错的,尽管仍然很耗时。)。
在最简单的形式中,该函数只以两个字符串作为参数,并计算通过插入、替换和删除等操作将str1转换成str2所需要的操作次数。
第二种变体将采用三个额外的参数来定义插入、替换和删除操作的次数。此变体比第一种更加通用和适应,但效率不高。
参数
str1
求编辑距离中的其中一个字符串
str2
求编辑距离中的另一个字符串
cost_ins
定义插入次数
cost_rep
定义替换次数
cost_del
定义删除次数
返回值
此函数返回两个字符串参数之间的编辑距离,如果其中一个字符串参数长度大于限制的255个字符时,返回-1。
范例
示例 #1 levenshtein 例子:
<?php
// 输入拼写错误的单词
$input = 'carrrot';
// 要检查的单词数组
$words = array('apple','pineapple','banana','orange',
'radish','carrot','pea','bean','potato');
// 目前没有找到最短距离
$shortest = -1;
// 遍历单词来找到最接近的
foreach ($words as $word) {
// 计算输入单词与当前单词的距离
$lev = levenshtein($input, $word);
// 检查完全的匹配
if ($lev == 0) {
// 最接近的单词是这个(完全匹配)
$closest = $word;
$shortest = 0;
// 退出循环;我们已经找到一个完全的匹配
break;
}
// 如果此次距离比上次找到的要短
// 或者还没找到接近的单词
if ($lev <= $shortest || $shortest < 0) {
// 设置最接近的匹配以及它的最短距离
$closest = $word;
$shortest = $lev;
}
}
echo "Input word: $input\n";
if ($shortest == 0) {
echo "Exact match found: $closest\n";
} else {
echo "Did you mean: $closest?\n";
}
?>
以上例程会输出:
Input word: carrrot
Did you mean: carrot?
参见
- soundex
- similar_text
- metaphone
localeconv
Get numeric formatting information
说明
array <span class="methodname">localeconv ( <span class="methodparam">void )
Returns an associative array containing localized numeric and monetary formatting information.
返回值
localeconv returns data based upon the current locale as set by setlocale. The associative array that is returned contains the following fields:
| Array element | Description |
|---|---|
| decimal_point | Decimal point character |
| thousands_sep | Thousands separator |
| grouping | Array containing numeric groupings |
| int_curr_symbol | International currency symbol (i.e. USD) |
| currency_symbol | Local currency symbol (i.e. $) |
| mon_decimal_point | Monetary decimal point character |
| mon_thousands_sep | Monetary thousands separator |
| mon_grouping | Array containing monetary groupings |
| positive_sign | Sign for positive values |
| negative_sign | Sign for negative values |
| int_frac_digits | International fractional digits |
| frac_digits | Local fractional digits |
| p_cs_precedes | true if currency_symbol precedes a positive value, false if it succeeds one |
| p_sep_by_space | true if a space separates currency_symbol from a positive value, false otherwise |
| n_cs_precedes | true if currency_symbol precedes a negative value, false if it succeeds one |
| n_sep_by_space | true if a space separates currency_symbol from a negative value, false otherwise |
| p_sign_posn |
|
| n_sign_posn |
|
The p_sign_posn, and n_sign_posn contain a string of formatting options. Each number representing one of the above listed conditions.
The grouping fields contain arrays that define the way numbers should be
grouped. For example, the monetary grouping field for the nl_NL locale
(in UTF-8 mode with the euro sign), would contain a 2 item array with
the values 3 and 3. The higher the index in the array, the farther left
the grouping is. If an array element is equal to CHAR_MAX, no
further grouping is done. If an array element is equal to 0, the
previous element should be used.
范例
示例 #1 localeconv example
<?php
if (false !== setlocale(LC_ALL, 'nl_NL.UTF-8@euro')) {
$locale_info = localeconv();
print_r($locale_info);
}
?>
以上例程会输出:
Array
(
[decimal_point] => .
[thousands_sep] =>
[int_curr_symbol] => EUR
[currency_symbol] => €
[mon_decimal_point] => ,
[mon_thousands_sep] =>
[positive_sign] =>
[negative_sign] => -
[int_frac_digits] => 2
[frac_digits] => 2
[p_cs_precedes] => 1
[p_sep_by_space] => 1
[n_cs_precedes] => 1
[n_sep_by_space] => 1
[p_sign_posn] => 1
[n_sign_posn] => 2
[grouping] => Array
(
)
[mon_grouping] => Array
(
[0] => 3
[1] => 3
)
)
参见
- setlocale
ltrim
删除字符串开头的空白字符(或其他字符)
说明
string ltrim (
string $str
[, string
$character_mask ] )
删除字符串开头的空白字符(或其他字符)
参数
str
输入的字符串。
character_mask
通过参数
character_mask,你也可以指定想要删除的字符,简单地列出你想要删除的所有字符即可。使用..,可以指定字符的范围。
返回值
该函数返回一个删除了 str 最左边的空白字符的字符串。
如果不使用第二个参数, ltrim
仅删除以下字符:
- " " (ASCII 32 (0x20)),普通空白字符。
- "\t" (ASCII 9 (0x09)), 制表符.
- "\n" (ASCII 10 (0x0A)),换行符。
- "\r" (ASCII 13 (0x0D)),回车符。
- "\0" (ASCII 0 (0x00)), NUL空字节符。
- "\x0B" (ASCII 11 (0x0B)),垂直制表符。
范例
示例 #1 ltrim的使用范例
<?php
$text = "\t\tThese are a few words :) ... ";
$binary = "\x09Example string\x0A";
$hello = "Hello World";
var_dump($text, $binary, $hello);
print "\n";
$trimmed = ltrim($text);
var_dump($trimmed);
$trimmed = ltrim($text, " \t.");
var_dump($trimmed);
$trimmed = ltrim($hello, "Hdle");
var_dump($trimmed);
// 删除 $binary 开头的 ASCII 控制字符
// (从 0 到 31,包括 0 和 31)
$clean = ltrim($binary, "\x00..\x1F");
var_dump($clean);
?>
以上例程会输出:
string(32) " These are a few words :) ... "
string(16) " Example string
"
string(11) "Hello World"
string(30) "These are a few words :) ... "
string(30) "These are a few words :) ... "
string(7) "o World"
string(15) "Example string
"
参见
- trim
- rtrim
md5_file
计算指定文件的 MD5 散列值
说明
string <span
class="methodname">md5_file ( <span
class="type">string $filename [, <span
class="methodparam">bool $raw_output<span
class="initializer"> = false ] )
使用
» RSA 数据安全公司的 MD5 报文算法计算
filename 文件的 MD5 散列值并返回。该散列值为 32 字符的十六进制数字。
参数
filename
文件名
raw_output
如果被设置为 true,那么报文摘要将以原始的 16 位二进制格式返回。
返回值
成功返回字符串,否则返回 false。
更新日志
| 版本 | 说明 |
|---|---|
| 5.1.0 | 函数改用流 API。这意味着能够配合封装器使用该函数,比如 md5_file('http://example.com/..')。 |
范例
示例 #1 md5_file 使用范例
<?php
$file = 'php-5.3.0alpha2-Win32-VC9-x64.zip';
echo 'MD5 file hash of ' . $file . ': ' . md5_file($file);
?>
参见
- md5
- sha1_file
- crc32
md5
计算字符串的 MD5 散列值
Warning
由于此函数依赖的算法已不足够复杂,不推荐使用此函数对明文密码加密。详细内容参见 这里。
说明
string md5 (
string $str
[, bool
$raw_output = false ] )
使用
» RSA 数据安全公司的 MD5 报文算法计算
str 的 MD5 散列值。
参数
str
原始字符串。
raw_output
如果可选的 raw_output 被设置为 true,那么 MD5
报文摘要将以16字节长度的原始二进制格式返回。
返回值
以 32 字符十六进制数字形式返回散列值。
范例
示例 #1 md5 范例
<?php
$str = 'apple';
if (md5($str) === '1f3870be274f6c49b3e31a0c6728957f') {
echo "Would you like a green or red apple?";
}
?>
参见
- md5_file
- sha1_file
- crc32
- sha1
- hash
- crypt
- password_hash
metaphone
Calculate the metaphone key of a string
说明
string <span
class="methodname">metaphone ( <span
class="type">string $string [, <span
class="methodparam">int $max_phonemes<span
class="initializer"> = 0 ] )
Calculates the metaphone key of string.
Similar to soundex metaphone creates the same key for similar sounding words. It's more accurate than <span class="function">soundex as it knows the basic rules of English pronunciation. The metaphone generated keys are of variable length.
Metaphone was developed by Lawrence Philips \<lphilips at verity dot com>. It is described in ["Practical Algorithms for Programmers", Binstock & Rex, Addison Wesley, 1995].
参数
string
The input string.
max_phonemes
This parameter restricts the returned metaphone key to max_phonemes
characters in length. However, the resulting phonemes are always
transcribed completely, so the resulting string length may be slightly
longer than max_phonemes. The default value of 0 means no
restriction.
返回值
Returns the metaphone key as a string.
更新日志
| 版本 | 说明 |
|---|---|
| 8.0.0 | The function returned false on failure. |
范例
示例 #1 metaphone basic example
<?php
var_dump(metaphone('programming'));
var_dump(metaphone('programmer'));
?>
以上例程会输出:
string(7) "PRKRMNK"
string(6) "PRKRMR"
示例 #2 Using the max_phonemes parameter
<?php
var_dump(metaphone('programming', 5));
var_dump(metaphone('programmer', 5));
?>
以上例程会输出:
string(5) "PRKRM"
string(5) "PRKRM"
示例 #3 Using the max_phonemes parameter
In this example, metaphone is advised to produce a string of five characters, but that would require to split the final phoneme ('x' is supposed to be transcribed to 'KS'), so the function returns a string with six characters.
<?php
var_dump(metaphone('Asterix', 5));
?>
以上例程会输出:
string(6) "ASTRKS"
money_format
将数字格式化成货币字符串
说明
string <span
class="methodname">money_format ( <span
class="methodparam">string $format ,
float
$number )
money_format 返回格式化好的 number
版本。 此函数包装了 C 函数库中的 <span
class="function">strfmon,不同之处是:此实现每次只能转化一个数字。
参数
format
格式字符串由以下几部分组成:
-
单个 % 字符
-
可选的标记(flags)
-
可选的字段宽度
-
可选的,左侧精度
-
可选的,右侧精度
-
必选的,单个转化字符
标记(Flags)
可选多个标记,分别是:
=f
字符:=,并紧跟一个字符(单字节) <span
class="replaceable">f,用于数字填充。默认的填充字符是空格。
^
禁用分组字符(比如金额中的逗号。在本地区域设置 locale 中定义)。
+ or (
正负数字的格式。使用 +,将使用区域设置(locale)中相当于 + 和 -
的符号。 如果使用 (,负数将被圆括号围绕。不设置的话,默认为 +。
!
不输出货币符号(比如 ¥)。
-
有这个符号的时候,将使字段左对齐(填充到右边),默认是相反的,是右对齐的(填充到左边)。
字段宽度
w
十进制数值字符串的宽度。字段将右对齐,除非使用了 - 标记。默认值 0。
左侧精度
#n
小数字符(比如小数点)前的最大位数 (<span
class="replaceable">n)。 常用于同一列中的格式对齐。 如果位数小于
n 则使用填充字符填满。 如果实际位数大于
n,此设置将被忽略。
如果没用 ^ 标识禁用分组,分组分隔符会在添加填充字符之前插入(如果有的话)。 分组分隔符不会应用到填充字符里,哪怕填充字符是个数字。
为了保证对齐,出现在之前或者之后的字符,都会填充必要的空格,保证正负情况下长度都一样。
右侧精度
.p
小数点后的一段数字 (p)。 如果 <span
class="replaceable">p 的值是 0(零),小数点右侧的数值将被删除。
如果不使用这个标记,默认展现取决于当前的区域设置。
小数点后指定位数的数字,四舍五入格式化。
转化字符
i
根据国际化区域设置中的货币格式,格式化数值。(比如,locale 是 USA:USD
1,234.56)。
n
根据国际化区域设置中国家的货币格式,格式化数值。(比如,locale 是
de_DE:EU1.234,56)。
%
返回字符 %。
number
需要格式化的数字。
返回值
返回格式化后的字符。格式字符串前后的字符将原封不动返回。 传入的 number
如果不是数字,将返回 null 并且产生 E_WARNING。
注释
Note:
具有 strfmon 的系统才有 money_format 函数。 例如 Windows 不具备,所以 Windows 系统上 <span class="function">money_format 未定义。
Note:
locale 设置中,
LC_MONETARY会影响此函数的行为。 在使用函数前,首先要用 setlocale 来设置合适的区域设置(locale)。
范例
示例 #1 money_format 例子
使用不同的 locale 和格式字符串,来说明此函数的用法。
<?php
$number = 1234.56;
// 让我们打印 en_US locale 的国际化格式
setlocale(LC_MONETARY, 'en_US');
echo money_format('%i', $number) . "\n";
// USD 1,234.56
// 意大利国家的格式,带两位浮点小数`
setlocale(LC_MONETARY, 'it_IT');
echo money_format('%.2n', $number) . "\n";
// Eu 1.234,56
// 负数的使用
$number = -1234.5672;
// 美国国家的格式,使用圆括号 () 标记负数。
// 左侧精度使用十位
setlocale(LC_MONETARY, 'en_US');
echo money_format('%(#10n', $number) . "\n";
// ($ 1,234.57)
// 相似的格式,添加了右侧两位小数点的精度,同时用 * 来填充
echo money_format('%=*(#10.2n', $number) . "\n";
// ($********1,234.57)
// 让我们左对齐,14位宽,左侧八位,右侧两位,不带分组字符
// de_DE 的国际化格式
setlocale(LC_MONETARY, 'de_DE');
echo money_format('%=*^-14#8.2i', 1234.56) . "\n";
// Eu 1234,56****
// 让我们在格式字符串前后,添加一些简介
setlocale(LC_MONETARY, 'en_GB');
$fmt = 'The final value is %i (after a 10%% discount)';
echo money_format($fmt, 1234.56) . "\n";
// The final value is GBP 1,234.56 (after a 10% discount)
?>
参见
- setlocale
- sscanf
- sprintf
- printf
- number_format
nl_langinfo
Query language and locale information
说明
string<span
class="type">false <span
class="methodname">nl_langinfo ( <span
class="type">int $item )
nl_langinfo is used to access individual elements of the locale categories. Unlike <span class="function">localeconv, which returns all of the elements, nl_langinfo allows you to select any specific element.
参数
item
item may be an integer value of the element or the constant name of
the element. The following is a list of constant names for item that
may be used and their description. Some of these constants may not be
defined or hold no value for certain locales.
nl_langinfo Constants
Constant
返回值
Returns the element as a string, or false if item is not valid.
注释
Note: 此函数未在 Windows 平台下实现。
参见
- setlocale
- localeconv
nl2br
在字符串所有新行之前插入 HTML 换行标记
说明
string nl2br (
string
$string [, <span
class="type">bool $is_xhtml =
true ] )
在字符串 string 所有新行之前插入 '<br />' 或 '<br>',并返回。
参数
string
输入字符串。
is_xhtml
是否使用 XHTML 兼容换行符。
返回值
返回调整后的字符串。
范例
示例 #1 nl2br 使用范例
<?php
echo nl2br("foo isn't\n bar");
?>
以上例程会输出:
foo isn't<br />
bar
示例 #2 使用 is_xhtml 生成合法的 HTML 标记
<?php
echo nl2br("Welcome\r\nThis is my HTML document", false);
?>
以上例程会输出:
Welcome<br>
This is my HTML document
示例 #3 各种换行分隔符
<?php
$string = "This\r\nis\n\ra\nstring\r";
echo nl2br($string);
?>
以上例程会输出:
This<br />
is<br />
a<br />
string<br />
更新日志
| 版本 | 说明 |
|---|---|
| 5.3.0 | 新增可选的 is_xhtml 参数。在此之前,总是插入 '\<br />'。 |
参见
- htmlspecialchars
- htmlentities
- wordwrap
- str_replace
number_format
以千位分隔符方式格式化一个数字
说明
string <span
class="methodname">number_format ( <span
class="methodparam">float $number [,
int $decimals<span
class="initializer"> = 0 ] )
string <span
class="methodname">number_format ( <span
class="methodparam">float $number ,
int $decimals<span
class="initializer"> = 0 , <span
class="type">string $dec_point =
"." , <span
class="type">string $thousands_sep =
"," )
本函数可以接受1个、2个或者4个参数(注意:不能是3个):
如果只提供第一个参数,number的小数部分会被去掉
并且每个千位分隔符都是英文小写逗号","
如果提供两个参数,number将保留小数点后的位数到你设定的值,其余同楼上
如果提供了四个参数,number 将保留decimals个长度的小数部分,
小数点被替换为dec_point,千位分隔符替换为thousands_sep
参数
number
你要格式化的数字
decimals
要保留的小数位数
dec_point
指定小数点显示的字符
thousands_sep
指定千位分隔符显示的字符
返回值
格式化以后的 number.
更新日志
| 版本 | 说明 |
|---|---|
| 5.4.0 | This function now supports multiple bytes in dec_point and thousands_sep. Only the first byte of each separator was used in older versions. |
范例
示例 #1 number_format Example
For instance, French notation usually use two decimals, comma (',') as decimal separator, and space (' ') as thousand separator. The following example demonstrates various way to format a number:
<?php
$number = 1234.56;
// english notation (default)
$english_format_number = number_format($number);
// 1,235
// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56
$number = 1234.5678;
// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57
?>
更新日志
| 版本 | 说明 |
|---|---|
| 7.2.0 | number_format 现在无法返回 -0,之前可能返回 -0,因为 number 可能会是 -0.01。 |
参见
- money_format
- sprintf
- printf
- sscanf
ord
转换字符串第一个字节为 0-255 之间的值
说明
int ord (
string
$string )
解析 string 二进制值第一个字节为 0 到 255 范围的无符号整型类型。
如果字符串是 ASCII、 ISO-8859、Windows 1252之类单字节编码,就等于返回该字符在字符集编码表中的位置。 但请注意,本函数不会去检测字符串的编码,尤其是不会识别类似 UTF-8 或 UTF-16 这种多字节字符的 Unicode 代码点(code point)。
该函数是 chr 的互补函数。
参数
string
一个字符。
返回值
返回 0 - 255 的整型值。
范例
示例 #1 ord 范例
<?php
$str = "\n";
if (ord($str) == 10) {
echo "The first character of \$str is a line feed.\n";
}
?>
示例 #2 检查 UTF-8 字符串的每一个字节
<?php
declare(encoding='UTF-8');
$str = "🐘";
for ( $pos=0; $pos < strlen($str); $pos ++ ) {
$byte = substr($str, $pos);
echo 'Byte ' . $pos . ' of $str has value ' . ord($byte) . PHP_EOL;
}
?>
以上例程会输出:
Byte 0 of $str has value 240
Byte 1 of $str has value 159
Byte 2 of $str has value 144
Byte 3 of $str has value 152
参见
- chr
- » ASCII 码表
parse_str
将字符串解析成多个变量
说明
void <span
class="methodname">parse_str ( <span
class="type">string $encoded_string [, <span
class="methodparam">array &$result ]
)
如果 encoded_string 是 URL 传递入的查询字符串(query
string),则将它解析为变量并设置到当前作用域(如果提供了 result
则会设置到该数组里 )。
参数
encoded_string
输入的字符串。
result
如果设置了第二个变量 result,
变量将会以数组元素的形式存入到这个数组,作为替代。
Warning
极度不建议 在没有 result 参数的情况下使用此函数,并且在 PHP 7.2
中将废弃不设置参数的行为。
在函数中动态设置变量会和 register_globals 有同样的问题。
阅读「安全」中 使用 Register Globals 的章节,解释了它为什么是危险的。
返回值
没有返回值。
更新日志
| 版本 | 说明 |
|---|---|
| 7.2.0 | 不带第二个参数的情况下使用 parse_str 会产生 E_DEPRECATED 警告。 |
范例
示例 #1 parse_str 的使用
<?php
$str = "first=value&arr[]=foo+bar&arr[]=baz";
// 推荐用法
parse_str($str, $output);
echo $output['first']; // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz
// 不建议这么用
parse_str($str);
echo $first; // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz
?>
由于 PHP 的变量名不能带「点」和「空格」,所以它们会被转化成下划线。
用本函数带 result 参数,也会应用同样规则到数组的键名。
示例 #2 parse_str 名称改写
<?php
parse_str("My Value=Something");
echo $My_Value; // Something
parse_str("My Value=Something", $output);
echo $output['My_Value']; // Something
?>
注释
Note:
所有创建的变量(或者在设置第二个参数的情况下,返回数组里的值), 都已经 urldecode 了。
Note:
要获取当前的 QUERY_STRING,可以使用
$_SERVER['QUERY_STRING']变量。 所以你可能想要阅读 来自 PHP 之外的变量这个章节。
Note:
本函数受 magic_quotes_gpc 设置的影响, 和
$_GET、$_POST在 PHP 中填充变量相似, <span class="function">parse_str 也使用了同样的机制。
参见
- parse_url
- pathinfo
- http_build_query
- urldecode
输出字符串
说明
int print (
string $arg
)
输出 arg。
print 实际上不是函数(而是语言结构),所以可以不用圆括号包围参数列表。
和 echo 最主要的区别: print 仅支持一个参数,并总是返回 1。
参数
arg
输入数据。
返回值
总是返回 1。
范例
示例 #1 print 范例
<?php
print("Hello World");
print "print() also works without parentheses.";
print "This spans
multiple lines. The newlines will be
output as well";
print "This spans\nmultiple lines. The newlines will be\noutput as well.";
print "escaping characters is done \"Like this\".";
// 可以在打印语句中使用变量
$foo = "foobar";
$bar = "barbaz";
print "foo is $foo"; // foo is foobar
// 也可以使用数组
$bar = array("value" => "foo");
print "this is {$bar['value']} !"; // this is foo !
// 使用单引号将打印变量名,而不是变量的值
print 'foo is $foo'; // foo is $foo
// 如果没有使用任何其他字符,可以仅打印变量
print $foo; // foobar
print <<<END
This uses the "here document" syntax to output
multiple lines with $variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon no extra whitespace!
END;
?>
注释
Note: <span class="simpara">因为是一个语言构造器而不是一个函数,不能被 可变函数 调用。
参见
- echo
- printf
- flush
- Heredoc syntax
printf
输出格式化字符串
说明
int printf (
string
$format [, <span
class="type">mixed $args [, <span
class="methodparam">mixed $... ]] )
依据 format 格式参数产生输出。
参数
format
format 描述信息,请参见 sprintf。
args
...
返回值
返回输出字符串的长度。
参见
- sprintf
- vprintf
- sscanf
- fscanf
- flush
quoted_printable_decode
将 quoted-printable 字符串转换为 8-bit 字符串
说明
string <span
class="methodname">quoted_printable_decode ( <span
class="methodparam">string $str )
该函数返回 quoted-printable 解码之后的 8-bit 字符串 (参考 » RFC2045 的6.7章节,而不是 » RFC2821 的4.5.2章节,so additional periods are not stripped from the beginning of line)
该函数与 imap_qprint 函数十分相似,但是该函数不需要依赖 IMAP 模块。
参数
str
输入的字符串。
返回值
返回的 8-bit 二进制字符串。
参见
- quoted_printable_encode
quoted_printable_encode
将 8-bit 字符串转换成 quoted-printable 字符串
说明
string <span
class="methodname">quoted_printable_encode ( <span
class="methodparam">string $str )
返回 quoted-printable 格式的字符,该格式由 » RFC2045 6.7.章节里制定。
该函数与 imap_8bit 函数十分相似,不同的是该函数不需要 IMAP 模块就能运行。
参数
str
输入的字符串。
返回值
返回编码之后的字符串。
参见
- quoted_printable_decode
- iconv_mime_encode
quotemeta
转义元字符集
说明
string <span
class="methodname">quotemeta ( <span
class="type">string $str )
返回 在下面这些特殊字符前加 反斜线(\) 转义后的字符串。 这些特殊字符包含:
. \ + * ? [ ^ ] ( $ )
参数
str
输入字符串
返回值
返回 元字符集被转义后的 字符串,如果输入字符串str为空, 则返回
false。
注释
Note: 此函数可安全用于二进制对象。
参见
- addslashes
- addcslashes
- htmlentities
- htmlspecialchars
- nl2br
- stripslashes
- stripcslashes
- ereg
- preg_quote
rtrim
删除字符串末端的空白字符(或者其他字符)
说明
string rtrim (
string $str
[, string
$character_mask ] )
该函数删除 str 末端的空白字符(或者其他字符)并返回。
不使用第二个参数,rtrim 仅删除以下字符:
- " " (ASCII 32 (0x20)),普通空白符。
- "\t" (ASCII 9 (0x09)),制表符。
- "\n" (ASCII 10 (0x0A)),换行符。
- "\r" (ASCII 13 (0x0D)),回车符。
- "\0" (ASCII 0 (0x00)),NUL 空字节符。
- "\x0B" (ASCII 11 (0x0B)),垂直制表符。
参数
str
输入字符串。
character_mask
通过指定
character_mask,可以指定想要删除的字符列表。简单地列出你想要删除的全部字符。使用
.. 格式,可以指定一个范围。
返回值
返回改变后的字符串。
范例
示例 #1 rtrim 使用范例
<?php
$text = "\t\tThese are a few words :) ... ";
$binary = "\x09Example string\x0A";
$hello = "Hello World";
var_dump($text, $binary, $hello);
print "\n";
$trimmed = rtrim($text);
var_dump($trimmed);
$trimmed = rtrim($text, " \t.");
var_dump($trimmed);
$trimmed = rtrim($hello, "Hdle");
var_dump($trimmed);
// 删除 $binary 末端的 ASCII 码控制字符
// (包括 0 - 31)
$clean = rtrim($binary, "\x00..\x1F");
var_dump($clean);
?>
以上例程会输出:
string(32) " These are a few words :) ... "
string(16) " Example string
"
string(11) "Hello World"
string(30) " These are a few words :) ..."
string(26) " These are a few words :)"
string(9) "Hello Wor"
string(15) " Example string"
参见
- trim
- ltrim
setlocale
设置地区信息
说明
string <span
class="methodname">setlocale ( <span
class="type">int $category , <span
class="methodparam">string $locale
[, string
$... ] )
string <span
class="methodname">setlocale ( <span
class="type">int $category , <span
class="methodparam">array $locale )
设置地区信息。
参数
category
category 命名常量指定的受区域设置的功能类别:
-
LC_ALL所有的设置 -
LC_COLLATE字符串比较, 详见 <span class="function">strcoll -
LC_CTYPE字符串的分类与转换, 参见例子 strtoupper -
LC_MONETARY等同 <span class="function">localeconv -
LC_NUMERIC对于小数点的分隔 (另请参见 localeconv) -
LC_TIME时间与格式 <span class="function">strftime -
LC_MESSAGES系统响应 (如果PHP使用libintl编译)
locale
If locale is null or the empty string "", the locale names
will be set from the values of environment variables with the same names
as the above categories, or from "LANG".
If locale is "0", the locale setting is not affected, only the
current setting is returned.
If locale is an array or followed by additional parameters then each
array element or parameter is tried to be set as new locale until
success. This is useful if a locale is known under different names on
different systems or for providing a fallback for a possibly not
available locale.
...
(可使用字符串或数组参数进行尝试直到设置成功。)
Note:
在Windows中,setlocale(LC_ALL, '')要从系统中的区域/语言设置(通过控制面板访问) 。
返回值
Returns the new current locale, or false if the locale
functionality is not implemented on your platform, the specified locale
does not exist or the category name is invalid.
An invalid category name also causes a warning message. Category/locale names can be found in » RFC 1766 and » ISO 639. Different systems have different naming schemes for locales.
Note:
The return value of setlocale depends on the system that PHP is running. It returns exactly what the system setlocale function returns.
更新日志
| 版本 | 说明 |
|---|---|
| 5.3.0 | This function now throws an E_DEPRECATED notice if a string is passed to the category parameter instead of one of the LC_* constants. |
范例
示例 #1 setlocale Examples
<?php
/* Set locale to Dutch */
setlocale(LC_ALL, 'nl_NL');
/* Output: vrijdag 22 december 1978 */
echo strftime("%A %e %B %Y", mktime(0, 0, 0, 12, 22, 1978));
/* try different possible locale names for german as of PHP 4.3.0 */
$loc_de = setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'de', 'ge');
echo "Preferred locale for german on this system is '$loc_de'";
?>
示例 #2 setlocale Examples for Windows
<?php
/* Set locale to Dutch */
setlocale(LC_ALL, 'nld_nld');
/* Output: vrijdag 22 december 1978 */
echo strftime("%A %d %B %Y", mktime(0, 0, 0, 12, 22, 1978));
/* try different possible locale names for german as of PHP 4.3.0 */
$loc_de = setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'deu_deu');
echo "Preferred locale for german on this system is '$loc_de'";
?>
注释
Warning
The locale information is maintained per process, not per thread. If you are running PHP on a multithreaded server API like IIS or Apache on Windows, you may experience sudden changes in locale settings while a script is running, though the script itself never called <span class="function">setlocale. This happens due to other scripts running in different threads of the same process at the same time, changing the process-wide locale using <span class="function">setlocale.
小贴士
Windows users will find useful information about locale strings at
Microsoft's MSDN website. Supported language strings can be found in the
» language strings documentation
and supported country/region strings in the
» country/region strings documentation.
sha1_file
计算文件的 sha1 散列值
说明
string <span
class="methodname">sha1_file ( <span
class="type">string $filename [, <span
class="methodparam">bool $raw_output<span
class="initializer"> = false ] )
利用
» 美国安全散列算法 1,计算并返回由
filename 指定的文件的 sha1 散列值。该散列值是一个 40
字符长度的十六进制数字。
参数
filename
要散列的文件的文件名。
raw_output
如果被设置为 true,sha1 摘要将以 20 字符长度的原始格式返回。
返回值
成功返回一个字符串,否则返回 false。
范例
示例 #1 sha1_file 范例
<?php
foreach(glob('/home/Kalle/myproject/*.php') as $ent)
{
if(is_dir($ent))
{
continue;
}
echo $ent . ' (SHA1: ' . sha1_file($ent) . ')', PHP_EOL;
}
?>
参见
- sha1
- md5_file
- crc32
sha1
计算字符串的 sha1 散列值
Warning
由于此函数依赖的算法已不足够复杂,不推荐使用此函数对明文密码加密。详细内容参见 这里。
说明
string sha1 (
string $str
[, bool
$raw_output = false ] )
利用» 美国安全散列算法 1 计算字符串的 sha1 散列值。
参数
str
输入字符串。
raw_output
如果可选的 raw_output 参数被设置为 true, 那么 sha1 摘要将以 20
字符长度的原始格式返回, 否则返回值是一个 40 字符长度的十六进制数字。
返回值
返回 sha1 散列值字符串。
范例
示例 #1 sha1 范例
<?php
$str = 'apple';
if (sha1($str) === 'd0be2dc421be4fcd0172e5afceea3970e2f3d940') {
echo "Would you like a green or red apple?";
}
?>
参见
- sha1_file
- crc32
- md5
- hash
- crypt
- password_hash
similar_text
计算两个字符串的相似度
说明
int <span
class="methodname">similar_text ( <span
class="methodparam">string $first ,
string
$second [, <span
class="type">float &$percent ] )
两个字符串的相似程度计算依据 Programming Classics: Implementing the World's Best Algorithms by Oliver (ISBN 0-131-00413-1) 的描述进行。注意该实现没有使用 Oliver 虚拟码中的堆栈,但是却进行了递归调用,这个做法可能会导致整个过程变慢或变快。也请注意,该算法的复杂度是 O(N**3),N 是最长字符串的长度。
参数
first
第一个字符串。
second
第二个字符串。
percent
通过引用方式传递第三个参数,similar_text
将计算相似程度百分数。
返回值
返回在两个字符串中匹配字符的数目。
参见
- levenshtein
- soundex
soundex
Calculate the soundex key of a string
说明
string soundex
( string
$string )
Calculates the soundex key of string.
Soundex keys have the property that words pronounced similarly produce the same soundex key, and can thus be used to simplify searches in databases where you know the pronunciation but not the spelling. This soundex function returns a string 4 characters long, starting with a letter.
This particular soundex function is one described by Donald Knuth in "The Art Of Computer Programming, vol. 3: Sorting And Searching", Addison-Wesley (1973), pp. 391-392.
参数
string
The input string.
返回值
Returns the soundex key as a string.
更新日志
| 版本 | 说明 |
|---|---|
| 8.0.0 | Prior to this version, calling the function with an empty string returned false for no particular reason. |
范例
示例 #1 Soundex Examples
<?php
soundex("Euler") == soundex("Ellery"); // E460
soundex("Gauss") == soundex("Ghosh"); // G200
soundex("Hilbert") == soundex("Heilbronn"); // H416
soundex("Knuth") == soundex("Kant"); // K530
soundex("Lloyd") == soundex("Ladd"); // L300
soundex("Lukasiewicz") == soundex("Lissajous"); // L222
?>
参见
- levenshtein
- metaphone
- similar_text
sprintf
Return a formatted string
说明
string sprintf
( string
$format , <span
class="type">mixed $values )
Returns a string produced according to the formatting string format.
参数
format
The format string is composed of zero or more directives: ordinary
characters (excluding %) that are copied directly to the result and
conversion specifications, each of which results in fetching its own
parameter.
A conversion specification follows this prototype: %[argnum$][flags][width][.precision]specifier.
Argnum
An integer followed by a dollar sign $, to specify which number argument to treat in the conversion.
| Flag | 说明 |
|---|---|
| - | Left-justify within the given field width; Right justification is the default |
| + | Prefix positive numbers with a plus sign +; Default only negative are prefixed with a negative sign. |
| (space) | Pads the result with spaces. This is the default. |
| 0 | Only left-pads numbers with zeros. With s specifiers this can also right-pad with zeros. |
| '(char) | Pads the result with the character (char). |
Width
An integer that says how many characters (minimum) this conversion should result in.
Precision
A period . followed by an integer who's meaning depends on the specifier:
- For e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6).
- For g and G specifiers: this is the maximum number of significant digits to be printed.
- For s specifier: it acts as a cutoff point, setting a maximum character limit to the string.
Note: If the period is specified without an explicit value for precision, 0 is assumed.
Note: Attempting to use a position specifier greater than
PHP_INT_MAXwill generate warnings.
| Specifier | 说明 |
|---|---|
| % | A literal percent character. No argument is required. |
| b | The argument is treated as an integer and presented as a binary number. |
| c | The argument is treated as an integer and presented as the character with that ASCII. |
| d | The argument is treated as an integer and presented as a (signed) decimal number. |
| e | The argument is treated as scientific notation (e.g. 1.2e+2). The precision specifier stands for the number of digits after the decimal point since PHP 5.2.1. In earlier versions, it was taken as number of significant digits (one less). |
| E | Like the e specifier but uses uppercase letter (e.g. 1.2E+2). |
| f | The argument is treated as a float and presented as a floating-point number (locale aware). |
| F | The argument is treated as a float and presented as a floating-point number (non-locale aware). Available as of PHP 5.0.3. |
| g | General format. Let P equal the precision if nonzero, 6 if the precision is omitted, or 1 if the precision is zero. Then, if a conversion with style E would have an exponent of X: If P > X ≥ −4, the conversion is with style f and precision P − (X + 1). Otherwise, the conversion is with style e and precision P − 1. |
| G | Like the g specifier but uses E and f. |
| o | The argument is treated as an integer and presented as an octal number. |
| s | The argument is treated and presented as a string. |
| u | The argument is treated as an integer and presented as an unsigned decimal number. |
| x | The argument is treated as an integer and presented as a hexadecimal number (with lowercase letters). |
| X | The argument is treated as an integer and presented as a hexadecimal number (with uppercase letters). |
Warning The c type specifier ignores padding and width
Warning Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results
Variables will be co-erced to a suitable type for the specifier:
| Type | Specifiers |
|---|---|
| string | s |
| integer | d, u, c, o, x, X, b |
| double | g, G, e, E, f, F |
values
返回值
Returns a string produced according to the formatting string format.
更新日志
| 版本 | 说明 |
|---|---|
| 8.0.0 | This function no longer returns false on failure. |
范例
示例 #1 Argument swapping
The format string supports argument numbering/swapping.
<?php
$num = 5;
$location = 'tree';
$format = 'There are %d monkeys in the %s';
echo sprintf($format, $num, $location);
?>
以上例程会输出:
There are 5 monkeys in the tree
However imagine we are creating a format string in a separate file, commonly because we would like to internationalize it and we rewrite it as:
<?php
$format = 'The %s contains %d monkeys';
echo sprintf($format, $num, $location);
?>
We now have a problem. The order of the placeholders in the format string does not match the order of the arguments in the code. We would like to leave the code as is and simply indicate in the format string which arguments the placeholders refer to. We would write the format string like this instead:
<?php
$format = 'The %2$s contains %1$d monkeys';
echo sprintf($format, $num, $location);
?>
An added benefit is that placeholders can be repeated without adding more arguments in the code.
<?php
$format = 'The %2$s contains %1$d monkeys.
That\'s a nice %2$s full of %1$d monkeys.';
echo sprintf($format, $num, $location);
?>
When using argument swapping, the n$ position specifier must come immediately after the percent sign (%), before any other specifiers, as shown below.
示例 #2 Specifying padding character
<?php
echo sprintf("%'.9d\n", 123);
echo sprintf("%'.09d\n", 123);
?>
以上例程会输出:
......123
000000123
示例 #3 Position specifier with other specifiers
<?php
$format = 'The %2$s contains %1$04d monkeys';
echo sprintf($format, $num, $location);
?>
以上例程会输出:
The tree contains 0005 monkeys
示例 #4 sprintf: zero-padded integers
<?php
$isodate = sprintf("%04d-%02d-%02d", $year, $month, $day);
?>
示例 #5 sprintf: formatting currency
<?php
$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;
echo $money;
echo "\n";
$formatted = sprintf("%01.2f", $money);
echo $formatted;
?>
以上例程会输出:
123.1
123.10
示例 #6 sprintf: scientific notation
<?php
$number = 362525200;
echo sprintf("%.3e", $number);
?>
以上例程会输出:
3.625e+8
参见
- printf
- fprintf
- vprintf
- vsprintf
- vfprintf
- sscanf
- fscanf
- number_format
- date
sscanf
根据指定格式解析输入的字符
说明
mixed sscanf (
string $str
, string
$format [, <span
class="type">mixed &$... ] )
这个函数 sscanf 输入类似 <span
class="function">printf。 sscanf
读取字符串str 然后根据指定格式format解析, 格式的描述文档见 <span
class="function">sprintf。
指定的格式字符串中的任意空白匹配输入字符串的任意空白.也就是说即使是格式字符串中的一个制表符 \t 也能匹配输入 字符串中的一个单一空格字符
参数
str
将要被解析的 字符串.
format
The interpreted format for 解析str的格式, 除了以下不同外,其余的见
sprintf的描述文档:
- 函数不区分语言地区
- F, g, G 和 b 不被支持.
- D 表示十进制数字.
- i stands for integer with base detection.
- n 代表目前已经处理的字符数。
- s 遇到任意空格字符时停止读取。
...
可以选参数将以引用方式传入,它们的值将被设置为解析匹配的值
返回值
如果仅传入了两个参数给这个函数,解析后将返回一个数组,否则,如果可选参数被传入,这个函数将返回被设置了值的个数
如果format存在的子字符串比 str内可用的多, -1 将被返回.
范例
示例 #1 sscanf 例子
<?php
// getting the serial number
list($serial) = sscanf("SN/2350001", "SN/%d");
// and the date of manufacturing
$mandate = "January 01 2000";
list($month, $day, $year) = sscanf($mandate, "%s %d %d");
echo "Item $serial was manufactured on: $year-" . substr($month, 0, 3) . "-$day\n";
?>
If optional parameters are passed, the function will return the number of assigned values.
示例 #2 sscanf - using optional parameters
<?php
// get author info and generate DocBook entry
$auth = "24\tLewis Carroll";
$n = sscanf($auth, "%d\t%s %s", $id, $first, $last);
echo "<author id='$id'>
<firstname>$first</firstname>
<surname>$last</surname>
</author>\n";
?>
参见
- fscanf
- printf
- sprintf
str_contains
Determine if a string contains a given substring
说明
bool <span
class="methodname">str_contains ( <span
class="methodparam">string $haystack
, string
$needle )
Performs a case-sensitive check indicating if needle is contained in
haystack.
参数
haystack
The string to search in.
needle
The substring to search for in the haystack.
返回值
Returns true if needle is in haystack, false otherwise.
范例
示例 #1 Using the empty string ''
<?php
if (str_contains('abc', '')) {
echo "Checking the existence of the empty string will always return true";
}
?>
以上例程会输出:
Checking the existence of the empty string will always return true
示例 #2 Showing case-sensitivity
<?php
$string = 'The lazy fox jumped over the fence';
if (str_contains($string, 'lazy')) {
echo "The string 'lazy' was found in the string\n";
}
if (str_contains($string, 'Lazy')) {
echo 'The string "Lazy" was found in the string';
} else {
echo '"Lazy" was not found because the case does not match';
}
?>
以上例程会输出:
The string 'lazy' was found in the string
"Lazy" was not found because the case does not match
注释
Note: 此函数可安全用于二进制对象。
参见
- str_ends_with
- str_starts_with
- stripos
- strrpos
- strripos
- strstr
- strpbrk
- substr
- preg_match
str_ends_with
Checks if a string ends with a given substring
说明
bool <span
class="methodname">str_ends_with ( <span
class="methodparam">string $haystack
, string
$needle )
Performs a case-sensitive check indicating if haystack ends with
needle.
参数
haystack
The string to search in.
needle
The substring to search for in the haystack.
返回值
Returns true if haystack ends with needle, false
otherwise.
范例
示例 #1 Using the empty string ''
<?php
if (str_ends_with('abc', '')) {
echo "All strings end with the empty string";
}
?>
以上例程会输出:
All strings end with the empty string
示例 #2 Showing case-sensitivity
<?php
$string = 'The lazy fox jumped over the fence';
if (str_ends_with($string, 'fence')) {
echo "The string ends with 'fence'\n";
}
if (str_ends_with($string, 'Fence')) {
echo 'The string ends with "fence"';
} else {
echo '"fence" was not found because the case does not match';
}
?>
以上例程会输出:
The string ends with 'fence'
"fence" was not found because the case does not match
注释
Note: 此函数可安全用于二进制对象。
参见
- str_contains
- str_starts_with
- stripos
- strrpos
- strripos
- strstr
- strpbrk
- substr
- preg_match
str_getcsv
解析 CSV 字符串为一个数组
说明
array <span
class="methodname">str_getcsv ( <span
class="type">string $input [, <span
class="methodparam">string $delimiter<span
class="initializer"> = "," [, <span
class="methodparam">string $enclosure<span
class="initializer"> = '"' [, <span
class="methodparam">string $escape<span
class="initializer"> = "\\" ]]] )
以 CSV 字段格式解析字符串输入,并返回包含读取字段的数组。
参数
input
待解析的字符串。
delimiter
设定字段界定符(仅单个字符)。
enclosure
设定字段包裹字符(仅单个字符)。
escape
设置转义字符(仅单个字符)。默认为反斜线(\)。
返回值
返回一个包含读取到的字段的索引数组。
参见
- fgetcsv
str_ireplace
str_replace 的忽略大小写版本
说明
mixed <span
class="methodname">str_ireplace ( <span
class="methodparam">mixed $search ,
mixed
$replace , <span
class="type">mixed $subject [, <span
class="methodparam">int &$count ] )
该函数返回一个字符串或者数组。该字符串或数组是将 subject 中全部的
search 都被 replace
替换(忽略大小写)之后的结果。如果没有一些特殊的替换规则,你应该使用该函数替换带有
i 修正符的 preg_replace 函数。
参数
如果 search 和 replace 为数组,那么 <span
class="function">str_ireplace 将对 subject
做二者的映射替换。如果 replace 的值的个数少于 search
的个数,多余的替换将使用空字符串来进行。如果 search 是一个数组而
replace 是一个字符串,那么 search
中每个元素的替换将始终使用这个字符串。
如果 search 或 replace 是数组,他们的元素将从头到尾一个个处理。
search
要搜索的值,就像是 needle。可以使用 array 来提供多个 needle。
replace
search 的替换值。一个数组可以被用来指定多重替换。
subject
要被搜索和替换的字符串或数组,就像是 haystack。
如果 subject 是一个数组,替换操作将遍历整个
subject,并且也将返回一个数组。
count
如果被指定,它的值将被设置为替换发生的次数。
返回值
返回替换后的字符串或者数组。
范例
示例 #1 str_ireplace 范例
<?php
$bodytag = str_ireplace("%body%", "black", "<body text=%BODY%>");
echo $bodytag; // <body text=black>
?>
注释
Note: 此函数可安全用于二进制对象。
Caution
Because str_ireplace replaces left to right, it might replace a previously inserted value when doing multiple replacements. Example #2 in the <span class="function">str_replace documentation demonstrates how this may affect you in practice.
参见
- str_replace
- preg_replace
- strtr
str_pad
使用另一个字符串填充字符串为指定长度
说明
string <span
class="methodname">str_pad ( <span
class="type">string $input , <span
class="methodparam">int $pad_length
[, string
$pad_string = " " [, <span
class="methodparam">int $pad_type<span
class="initializer"> = STR_PAD_RIGHT ]] )
该函数返回 input
被从左端、右端或者同时两端被填充到制定长度后的结果。如果可选的
pad_string 参数没有被指定,input 将被空格字符填充,否则它将被
pad_string 填充到指定长度。
参数
input
输入字符串。
pad_length
如果 pad_length
的值是负数,小于或者等于输入字符串的长度,不会发生任何填充,并会返回
input 。
pad_string
Note:
如果填充字符的长度不能被
pad_string整除,那么pad_string可能会被缩短。
pad_type
可选的 pad_type 参数的可能值为 STR_PAD_RIGHT,STR_PAD_LEFT
或 STR_PAD_BOTH。如果没有指定 pad_type,则假定它是
STR_PAD_RIGHT。
返回值
返回填充后的字符串。
范例
示例 #1 str_pad 范例
<?php
$input = "Alien";
echo str_pad($input, 10); // 输出 "Alien "
echo str_pad($input, 10, "-=", STR_PAD_LEFT); // 输出 "-=-=-Alien"
echo str_pad($input, 10, "_", STR_PAD_BOTH); // 输出 "__Alien___"
echo str_pad($input, 6, "___"); // 输出 "Alien_"
echo str_pad($input, 3, "*"); // 输出 "Alien"
?>
str_repeat
重复一个字符串
说明
string <span
class="methodname">str_repeat ( <span
class="type">string $input , <span
class="methodparam">int $multiplier )
返回 input 重复 multiplier 次后的结果。
参数
input
待操作的字符串。
multiplier
input 被重复的次数。
multiplier 必须大于等于 0。如果 multiplier 被设置为
0,函数返回空字符串。
返回值
返回重复后的字符串。
范例
示例 #1 str_repeat 范例
<?php
echo str_repeat("-=", 10);
?>
以上例程会输出:
-=-=-=-=-=-=-=-=-=-=
参见
- for
- str_pad
- substr_count
str_replace
子字符串替换
说明
mixed <span
class="methodname">str_replace ( <span
class="type">mixed $search , <span
class="methodparam">mixed $replace ,
mixed
$subject [, <span
class="type">int &$count ] )
该函数返回一个字符串或者数组。该字符串或数组是将 subject 中全部的
search 都被 replace 替换之后的结果。
如果没有一些特殊的替换需求(比如正则表达式),你应该使用该函数替换 <span class="function">ereg_replace 和 <span class="function">preg_replace。
参数
如果 search 和 replace 为数组,那么 <span
class="function">str_replace 将对 subject
做二者的映射替换。如果 replace 的值的个数少于 search
的个数,多余的替换将使用空字符串来进行。如果 search 是一个数组而
replace 是一个字符串,那么 search
中每个元素的替换将始终使用这个字符串。该转换不会改变大小写。
如果 search 和 replace 都是数组,它们的值将会被依次处理。
search
查找的目标值,也就是 needle。一个数组可以指定多个目标。
replace
search 的替换值。一个数组可以被用来指定多重替换。
subject
执行替换的数组或者字符串。也就是 haystack。
如果 subject 是一个数组,替换操作将遍历整个
subject,返回值也将是一个数组。
count
如果被指定,它的值将被设置为替换发生的次数。
返回值
该函数返回替换后的数组或者字符串。
范例
示例 #1 str_replace 基本范例
<?php
// 赋值: <body text='black'>
$bodytag = str_replace("%body%", "black", "<body text='%body%'>");
// 赋值: Hll Wrld f PHP
$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");
// 赋值: You should eat pizza, beer, and ice cream every day
$phrase = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables", "fiber");
$yummy = array("pizza", "beer", "ice cream");
$newphrase = str_replace($healthy, $yummy, $phrase);
// 赋值: 2
$str = str_replace("ll", "", "good golly miss molly!", $count);
echo $count;
?>
示例 #2 可能的 str_replace 替换范例
<?php
// 替换顺序
$str = "Line 1\nLine 2\rLine 3\r\nLine 4\n";
$order = array("\r\n", "\n", "\r");
$replace = '<br />';
// 首先替换 \r\n 字符,因此它们不会被两次转换
$newstr = str_replace($order, $replace, $str);
// 输出 F ,因为 A 被 B 替换,B 又被 C 替换,以此类推...
// 由于从左到右依次替换,最终 E 被 F 替换
$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';
echo str_replace($search, $replace, $subject);
// 输出: apearpearle pear
// 由于上面提到的原因
$letters = array('a', 'p');
$fruit = array('apple', 'pear');
$text = 'a p';
$output = str_replace($letters, $fruit, $text);
echo $output;
?>
注释
Note: 此函数可安全用于二进制对象。
Caution
由于 str_replace 的替换时从左到右依次进行的,进行多重替换的时候可能会替换掉之前插入的值。参见该文档的范例。
Note:
该函数区分大小写。使用 str_ireplace 可以进行不区分大小写的替换。
参见
- str_ireplace
- substr_replace
- preg_replace
- strtr
str_rot13
对字符串执行 ROT13 转换
说明
string <span
class="methodname">str_rot13 ( <span
class="type">string $str )
对 str 参数执行 ROT13 编码并将结果字符串返回。
ROT13 编码简单地使用字母表中后面第 13 个字母替换当前字母,同时忽略非字母表中的字符。编码和解码都使用相同的函数,传递一个编码过的字符串作为参数,将得到原始字符串。
参数
str
输入字符串。
返回值
返回给定字符串的 ROT13 版本。
范例
示例 #1 str_rot13 范例
<?php
echo str_rot13('PHP 4.3.0'); // CUC 4.3.0
?>
str_shuffle
随机打乱一个字符串
说明
string <span
class="methodname">str_shuffle ( <span
class="type">string $str )
str_shuffle 函数打乱一个字符串,使用任何一种可能的排序方案。
Caution
本函数并不会生成安全加密的值,不应用于加密用途。若需要安全加密的值,考虑使用 random_int、<span class="function">random_bytes 或 <span class="function">openssl_random_pseudo_bytes 替代。
参数
str
输入字符串。
返回值
返回打乱后的字符串。
更新日志
| 版本 | 说明 |
|---|---|
| 7.1.0 | 内置的随机算法从 libc rand 函数改成了» 梅森旋转演伪随机数发生算法。 |
范例
示例 #1 str_shuffle 范例
<?php
$str = 'abcdef';
$shuffled = str_shuffle($str);
// 输出类似于: bfdaec
echo $shuffled;
?>
参见
- shuffle
- rand
str_split
将字符串转换为数组
说明
array <span
class="methodname">str_split ( <span
class="type">string $string [, <span
class="methodparam">int $split_length<span
class="initializer"> = 1 ] )
将一个字符串转换为数组。
参数
string
输入字符串。
split_length
每一段的长度。
返回值
如果指定了可选的 split_length 参数,返回数组中的每个元素均为一个长度为
split_length 的字符块,否则每个字符块为单个字符。
如果 split_length 小于 1,返回 false。如果 split_length
参数超过了 string 超过了字符串 string
的长度,整个字符串将作为数组仅有的一个元素返回。
范例
示例 #1 str_split 使用范例
<?php
$str = "Hello Friend";
$arr1 = str_split($str);
$arr2 = str_split($str, 3);
print_r($arr1);
print_r($arr2);
?>
以上例程会输出:
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
)
注释
Note:
在处理多字节字符时,str_split 会按字节数转换,而非字符数。
参见
- chunk_split
- preg_split
- explode
- count_chars
- str_word_count
- for
str_starts_with
Checks if a string starts with a given substring
说明
bool <span
class="methodname">str_starts_with ( <span
class="methodparam">string $haystack
, string
$needle )
Performs a case-sensitive check indicating if haystack begins with
needle.
参数
haystack
The string to search in.
needle
The substring to search for in the haystack.
返回值
Returns true if haystack begins with needle, false
otherwise.
范例
示例 #1 Using the empty string ''
<?php
if (str_starts_with('abc', '')) {
echo "All strings start with the empty string";
}
?>
以上例程会输出:
All strings start with the empty string
示例 #2 Showing case-sensitivity
<?php
$string = 'The lazy fox jumped over the fence';
if (str_starts_with($string, 'The')) {
echo "The string starts with 'The'\n";
}
if (str_starts_with($string, 'the')) {
echo 'The string starts with "the"';
} else {
echo '"the" was not found because the case does not match';
}
?>
以上例程会输出:
The string starts with 'The'
"the" was not found because the case does not match
注释
Note: 此函数可安全用于二进制对象。
参见
- str_contains
- str_ends_with
- stripos
- strrpos
- strripos
- strstr
- strpbrk
- substr
- preg_match
str_word_count
返回字符串中单词的使用情况
说明
mixed <span
class="methodname">str_word_count ( <span
class="methodparam">string $string
[, int
$format = 0 [, <span
class="methodparam">string $charlist
]] )
统计 string 中单词的数量。如果可选的参数 format
没有被指定,那么返回值是一个代表单词数量的整型数。如果指定了 format
参数,返回值将是一个数组,数组的内容则取决于 format 参数。format
的可能值和相应的输出结果如下所列。
对于这个函数的目的来说,单词的定义是一个与区域设置相关的字符串。这个字符串可以包含字母字符,也可以包含 "'" 和 "-" 字符(但不能以这两个字符开始)。
参数
string
字符串。
format
指定函数的返回值。当前支持的值如下:
- 0 - 返回单词数量
- 1 - 返回一个包含
string中全部单词的数组 - 2 - 返回关联数组。数组的键是单词在
string中出现的数值位置,数组的值是这个单词
charlist
附加的字符串列表,其中的字符将被视为单词的一部分。
返回值
返回一个数组或整型数,这取决于 format 参数的选择。
范例
示例 #1 str_word_count 范例
<?php
$str = "Hello fri3nd, you're
looking good today!";
print_r(str_word_count($str, 1));
print_r(str_word_count($str, 2));
print_r(str_word_count($str, 1, 'àáãç3'));
echo str_word_count($str);
?>
以上例程会输出:
Array
(
[0] => Hello
[1] => fri
[2] => nd
[3] => you're
[4] => looking
[5] => good
[6] => today
)
Array
(
[0] => Hello
[6] => fri
[10] => nd
[14] => you're
[29] => looking
[46] => good
[51] => today
)
Array
(
[0] => Hello
[1] => fri3nd
[2] => you're
[3] => looking
[4] => good
[5] => today
)
7
参见
- explode
- preg_split
- split
- count_chars
- substr_count
strcasecmp
二进制安全比较字符串(不区分大小写)
说明
int strcasecmp
( string
$str1 , <span
class="type">string $str2 )
二进制安全比较字符串(不区分大小写)。
参数
str1
第一个字符串。
str2
第二个字符串。
返回值
如果 str1 小于 str2 返回 \< 0; 如果 str1 大于 str2 返回 >
0;如果两者相等,返回 0。
范例
示例 #1 strcasecmp 范例
<?php
$var1 = "Hello";
$var2 = "hello";
if (strcasecmp($var1, $var2) == 0) {
echo '$var1 is equal to $var2 in a case-insensitive string comparison';
}
?>
参见
- strcmp
- preg_match
- substr_compare
- strncasecmp
- stristr
- substr
strchr
别名 strstr
说明
此函数是该函数的别名: strstr.
strcmp
二进制安全字符串比较
说明
int strcmp (
string
$str1 , <span
class="type">string $str2 )
注意该比较区分大小写。
参数
str1
第一个字符串。
str2
第二个字符串。
返回值
如果 str1 小于 str2 返回 \< 0; 如果 str1 大于 str2 返回 >
0;如果两者相等,返回 0。
范例
示例 #1 strcmp 例子
<?php
$var1 = "Hello";
$var2 = "hello";
if (strcmp($var1, $var2) !== 0) {
echo '$var1 is not equal to $var2 in a case sensitive string comparison';
}
?>
参见
- strcasecmp
- preg_match
- substr_compare
- strncmp
- strstr
- substr
strcoll
基于区域设置的字符串比较
说明
int strcoll (
string
$str1 , <span
class="type">string $str2 )
注意该比较区分大小写。和 strcmp 不同,该函数不是二进制安全的。
strcoll 使用当前区域设置进行比较。如果当前区域为 C 或 POSIX,该函数等同于 <span class="function">strcmp。
参数
str1
第一个字符串。
str2
第二个字符串。
返回值
如果 str1 小于 str2 返回 \< 0; 如果 str1 大于 str2 返回 >
0;如果两者相等,返回 0。
更新日志
| 版本 | 说明 |
|---|---|
| 4.2.3 | 函数在 Win32 平台可用。 |
参见
- preg_match
- strcmp
- strcasecmp
- substr
- stristr
- strncasecmp
- strncmp
- strstr
- setlocale
strcspn
获取不匹配遮罩的起始子字符串的长度
说明
int strcspn (
string
$str1 , <span
class="type">string $str2 [, <span
class="methodparam">int $start [,
int $length
]] )
返回 str1 中,所有字符都不存在于 str2 范围的起始子字符串的长度。
参数
str1
第一个字符串。
str2
第二个字符串。
start
查找的起始位置。
length
查找的长度。
返回值
以整型数返回子串的长度。
范例
示例 #1 strcspn example
<?php
$a = strcspn('abcd', 'apple');
$b = strcspn('abcd', 'banana');
$c = strcspn('hello', 'l');
$d = strcspn('hello', 'world');
var_dump($a);
var_dump($b);
var_dump($c);
var_dump($d);
?>
以上例程会输出:
int(0)
int(0)
int(2)
int(2)
注释
Note: 此函数可安全用于二进制对象。
参见
- strspn
strip_tags
从字符串中去除 HTML 和 PHP 标记
说明
string <span
class="methodname">strip_tags ( <span
class="type">string $str [, <span
class="methodparam">string
$allowable_tags ] )
该函数尝试返回给定的字符串 str 去除空字符、HTML 和 PHP
标记后的结果。它使用与函数 fgetss
一样的机制去除标记。
参数
str
输入字符串。
allowable_tags
使用可选的第二个参数指定不被去除的字符列表。
Note:
HTML 注释和 PHP 标签也会被去除。这里是硬编码处理的,所以无法通过
allowable_tags参数进行改变。
Note:
In PHP 5.3.4 and later, self-closing XHTML tags are ignored and only non-self-closing tags should be used in
allowable_tags. For example, to allow both \<br> and \<br/>, you should use:<?php strip_tags($input, '<br>'); ?>
返回值
返回处理后的字符串。
更新日志
| 版本 | 说明 |
|---|---|
| 5.3.4 | strip_tags ignores self-closing XHTML tags in allowable_tags. |
| 5.0.0 | strip_tags 变为二进制安全的。 |
范例
示例 #1 strip_tags 范例
<?php
$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
echo strip_tags($text);
echo "\n";
// 允许 <p> 和 <a>
echo strip_tags($text, '<p><a>');
?>
以上例程会输出:
Test paragraph. Other text
<p>Test paragraph.</p> <a href="#fragment">Other text</a>
注释
Warning
由于 strip_tags 无法实际验证 HTML,不完整或者破损标签将导致更多的数据被删除。
Warning
该函数不会修改 allowable_tags 参数中指定的允许标记的任何属性,包括
style 和 onmouseover
属性,用户可能会在提交的内容中恶意滥用这些属性,从而展示给其他用户。
Note:
输入 HTML 标签名字如果大于 1023 字节(bytes)将会被认为是无效的,无论
allowable_tags参数是怎样的。
参见
- htmlspecialchars
stripcslashes
反引用一个使用 addcslashes 转义的字符串
说明
string <span
class="methodname">stripcslashes ( <span
class="methodparam">string $str )
返回反转义后的字符串。可识别类似 C 语言的 \n,\r,... 八进制以及十六进制的描述。
参数
str
需要反转义的字符串。
返回值
返回反转义后的字符串。
参见
- addcslashes
stripos
查找字符串首次出现的位置(不区分大小写)
说明
int stripos (
string
$haystack , <span
class="type">string $needle [, <span
class="methodparam">int $offset<span
class="initializer"> = 0 ] )
返回在字符串 haystack 中 needle
首次出现的数字位置。
与 strpos 不同,<span class="function">stripos 不区分大小写。
参数
haystack
在该字符串中查找。
needle
注意 needle 可以是一个单字符或者多字符的字符串。
如果 needle 不是一个字符串,那么它将被转换为整型并被视为字符顺序值。
offset
可选的 offset 参数,从字符此数量的开始位置进行搜索。
如果是负数,就从字符末尾此数量的字符数开始统计。
返回值
返回 needle 存在于 haystack
字符串开始的位置(独立于偏移量)。同时注意字符串位置起始于 0,而不是 1。
如果未发现 needle 将返回 false。
Warning
此函数可能返回布尔值 false,但也可能返回等同于 false
的非布尔值。请阅读
布尔类型章节以获取更多信息。应使用
=== 运算符来测试此函数的返回值。
更新日志
| 版本 | 说明 |
|---|---|
| 7.1.0 | 开始支持负数的 offset。 |
范例
示例 #1 stripos 范例
<?php
$findme = 'a';
$mystring1 = 'xyz';
$mystring2 = 'ABC';
$pos1 = stripos($mystring1, $findme);
$pos2 = stripos($mystring2, $findme);
// 'a' 当然不在 'xyz' 中
if ($pos1 === false) {
echo "The string '$findme' was not found in the string '$mystring1'";
}
// 注意这里使用的是 ===。简单的 == 不能像我们期望的那样工作,
// 因为 'a' 的位置是 0(第一个字符)。
if ($pos2 !== false) {
echo "We found '$findme' in '$mystring2' at position $pos2";
}
?>
注释
Note: 此函数可安全用于二进制对象。
参见
- mb_stripos
- strpos
- strrpos
- strripos
- stristr
- substr
- str_ireplace
stripslashes
反引用一个引用字符串
说明
string <span
class="methodname">stripslashes ( <span
class="type">string $str )
反引用一个引用字符串。
Note:
如果 magic_quotes_sybase 项开启,反斜线将被去除,但是两个反斜线将会被替换成一个。
一个使用范例是使用 PHP 检测 magic_quotes_gpc 配置项的 开启情况(在 PHP 5.4之 前默认是开启的)并且你不需要将数据插入到一个需要转义的位置(例如数据库)。例如,你只是简单地将表单数据直接输出。
参数
str
输入字符串。
返回值
返回一个去除转义反斜线后的字符串(\' 转换为 ' 等等)。双反斜线(\\*)被转换为单个反斜线(\*)。
范例
示例 #1 stripslashes 范例
<?php
$str = "Is your name O\'reilly?";
// 输出: Is your name O'reilly?
echo stripslashes($str);
?>
Note:
stripslashes 是非递归的。如果你想要在多维数组中使用该函数,你需要使用递归函数。
示例 #2 对数组使用 stripslashes
<?php
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
// 范例
$array = array("f\\'oo", "b\\'ar", array("fo\\'o", "b\\'ar"));
$array = stripslashes_deep($array);
// 输出
print_r($array);
?>
以上例程会输出:
Array
(
[0] => f'oo
[1] => b'ar
[2] => Array
(
[0] => fo'o
[1] => b'ar
)
)
参见
- addslashes
- get_magic_quotes_gpc
stristr
strstr 函数的忽略大小写版本
说明
string stristr
( string
$haystack , <span
class="type">mixed $needle [, <span
class="methodparam">bool $before_needle<span
class="initializer"> = false ] )
返回 haystack 字符串从 needle 第一次出现的位置开始到结尾的字符串。
参数
haystack
在该字符串中查找。
needle
如果 needle 不是一个字符串,那么它将被转换为整型并被视为字符顺序值。
before_needle
若为 true,strstr 将返回 needle 在
haystack 中的位置之前的部分(不包括 needle)。
参数 needle 和 haystack 将以不区分大小写的方式对待。
返回值
返回匹配的子字符串。如果 needle 未找到,返回 false。
更新日志
| 版本 | 说明 |
|---|---|
| 5.3.0 | 新增可选的 before_needle 参数。 |
| 4.3.0 | stristr 变为二进制安全的。 |
范例
示例 #1 stristr 范例
<?php
$email = '[email protected]';
echo stristr($email, 'e'); // 输出 [email protected]
echo stristr($email, 'e', true); // 自 PHP 5.3.0 起,输出 US
?>
示例 #2 测试字符串的存在与否
<?php
$string = 'Hello World!';
if(stristr($string, 'earth') === FALSE) {
echo '"earth" not found in string';
}
// 输出: "earth" not found in string
?>
示例 #3 使用非字符串 needle
<?php
$string = 'APPLE';
echo stristr($string, 97); // 97 = 小写字母 a
// 输出: APPLE
?>
注释
Note: 此函数可安全用于二进制对象。
参见
- strstr
- strrchr
- stripos
- strpbrk
- preg_match
strlen
获取字符串长度
说明
int strlen (
string
$string )
返回给定的字符串 string 的长度。
参数
string
需要计算长度的字符串。
返回值
成功则返回字符串 string 的长度;如果 string 为空,则返回 0。
更新日志
| 版本 | 说明 |
|---|---|
| 5.3.0 | Prior versions treated arrays as the string Array, thus returning a string length of 5 and emitting an E_NOTICE level error. |
范例
示例 #1 strlen 范例
<?php
$str = 'abcdef';
echo strlen($str); // 6
$str = ' ab cd ';
echo strlen($str); // 7
?>
注释
Note:
strlen returns the number of bytes rather than the number of characters in a string.
Note:
strlen returns
nullwhen executed on arrays, and anE_WARNINGlevel error is emitted.
参见
- count
- mb_strlen
strnatcasecmp
使用“自然顺序”算法比较字符串(不区分大小写)
说明
int <span
class="methodname">strnatcasecmp ( <span
class="methodparam">string $str1 ,
string
$str2 )
该函数实现了以人类习惯对数字型字符串进行排序的比较算法。除了不区分大小写,该函数的行为与 strnatcmp 类似。更多信息,参见:Martin Pool 的» 自然顺序的字符串比较页面。
参数
str1
第一个字符串。
str2
第二个字符串。
返回值
与其他字符串比较函数类似,如果 str1 小于 str2 返回 \< 0; 如果
str1 大于 str2 返回 > 0;如果两者相等,返回 0。
参见
- preg_match
- strcmp
- strcasecmp
- substr
- stristr
- strncasecmp
- strncmp
- strstr
- setlocale
strnatcmp
使用自然排序算法比较字符串
说明
int strnatcmp
( string
$str1 , <span
class="type">string $str2 )
该函数实现了以人类习惯对数字型字符串进行排序的比较算法,这就是“自然顺序”。注意该比较区分大小写。
参数
str1
第一个字符串。
str2
第二个字符串。
返回值
与其他字符串比较函数类似,如果 str1 小于 str2 返回 \< 0; 如果
str1 大于 str2 返回 > 0;如果两者相等,返回 0。
范例
下面的例子展示了该算法与计算机常规字符串比较算法( <span class="function">strcmp 所使用的)的区别:
<?php
$arr1 = $arr2 = array("img12.png", "img10.png", "img2.png", "img1.png");
echo "Standard string comparison\n";
usort($arr1, "strcmp");
print_r($arr1);
echo "\nNatural order string comparison\n";
usort($arr2, "strnatcmp");
print_r($arr2);
?>
以上例程会输出:
Standard string comparison
Array
(
[0] => img1.png
[1] => img10.png
[2] => img12.png
[3] => img2.png
)
Natural order string comparison
Array
(
[0] => img1.png
[1] => img2.png
[2] => img10.png
[3] => img12.png
)
更多信息,参见:Martin Pool 的» 自然顺序的字符串比较 page.
参见
- preg_match
- strcasecmp
- substr
- stristr
- strcmp
- strncmp
- strncasecmp
- strnatcasecmp
- strstr
- natsort
- natcasesort
strncasecmp
二进制安全比较字符串开头的若干个字符(不区分大小写)
说明
int <span
class="methodname">strncasecmp ( <span
class="type">string $str1 , <span
class="methodparam">string $str2 ,
int $len )
该函数与 strcasecmp 类似,不同之处在于你可以指定两个字符串比较时使用的长度(即最大比较长度)。
参数
str1
第一个字符串。
str2
第二个字符串。
len
最大比较长度。
返回值
如果 str1 小于 str2 返回 \< 0; 如果 str1 大于 str2 返回 >
0;如果两者相等,返回 0。
参见
- strncmp
- preg_match
- substr_compare
- strcasecmp
- stristr
- substr
strncmp
二进制安全比较字符串开头的若干个字符
说明
int strncmp (
string
$str1 , <span
class="type">string $str2 , <span
class="methodparam">int $len )
该函数与 strcmp 类似,不同之处在于你可以指定两个字符串比较时使用的长度(即最大比较长度)。
注意该比较区分大小写。
参数
str1
第一个字符串。
str2
第二个字符串。
len
最大比较长度。
返回值
如果 str1 小于 str2 返回 \< 0; 如果 str1 大于 str2 返回 >
0;如果两者相等,返回 0。
参见
- strncasecmp
- preg_match
- substr_compare
- strcmp
- strstr
- substr
strpbrk
在字符串中查找一组字符的任何一个字符
说明
string strpbrk
( string
$haystack , <span
class="type">string $char_list )
strpbrk 函数在 haystack 字符串中查找
char_list 中的字符。
参数
haystack
在此字符串中查找 char_list。
char_list
该参数区分大小写。
返回值
返回一个以找到的字符开始的子字符串。如果没有找到,则返回 false。
范例
示例 #1 strpbrk 范例
<?php
$text = 'This is a Simple text.';
// 输出 "is is a Simple text.",因为 'i' 先被匹配
echo strpbrk($text, 'mi');
// 输出 "Simple text.",因为字符区分大小写
echo strpbrk($text, 'S');
?>
参见
- strpos
- strstr
- preg_match
strpos
查找字符串首次出现的位置
说明
int strpos (
string
$haystack , <span
class="type">mixed $needle [, <span
class="methodparam">int $offset<span
class="initializer"> = 0 ] )
返回 needle 在 haystack 中首次出现的数字位置。
参数
haystack
在该字符串中进行查找。
needle
If needle is not a string, it is converted to an integer and applied
as the ordinal value of a character. This behavior is deprecated as of
PHP 7.3.0, and relying on it is highly discouraged. Depending on the
intended behavior, the needle should either be explicitly cast to
string, or an explicit call to chr should
be performed.
offset
如果提供了此参数,搜索会从字符串该字符数的起始位置开始统计。
如果是负数,搜索会从字符串结尾指定字符数开始。
返回值
返回 needle 存在于 haystack 字符串起始的位置(独立于
offset)。同时注意字符串位置是从0开始,而不是从1开始的。
如果没找到 needle,将返回 false。
Warning
此函数可能返回布尔值 false,但也可能返回等同于 false
的非布尔值。请阅读
布尔类型章节以获取更多信息。应使用
=== 运算符来测试此函数的返回值。
更新日志
| 版本 | 说明 |
|---|---|
| 7.1.0 | 开始支持负数的 offset。 |
范例
示例 #1 使用 ===
<?php
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);
// 注意这里使用的是 ===。简单的 == 不能像我们期待的那样工作,
// 因为 'a' 是第 0 位置上的(第一个)字符。
if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'";
} else {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
}
?>
示例 #2 使用 !==
<?php
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);
// 使用 !== 操作符。使用 != 不能像我们期待的那样工作,
// 因为 'a' 的位置是 0。语句 (0 != false) 的结果是 false。
if ($pos !== false) {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
} else {
echo "The string '$findme' was not found in the string '$mystring'";
}
?>
示例 #3 使用位置偏移量
<?php
// 忽视位置偏移量之前的字符进行查找
$newstring = 'abcdef abcdef';
$pos = strpos($newstring, 'a', 1); // $pos = 7, 不是 0
?>
注释
Note: 此函数可安全用于二进制对象。
参见
- stripos
- strrpos
- strripos
- strstr
- strpbrk
- substr
- preg_match
strrchr
查找指定字符在字符串中的最后一次出现
说明
string strrchr
( string
$haystack , <span
class="type">mixed $needle )
该函数返回 haystack 字符串中的一部分,这部分以 needle
的最后出现位置开始,直到 haystack 末尾。
参数
haystack
在该字符串中查找。
needle
如果 needle 包含了不止一个字符,那么仅使用第一个字符。该行为不同于
strstr。
如果 needle 不是一个字符串,那么将被转化为整型并被视为字符顺序值。
返回值
该函数返回字符串的一部分。如果 needle 未被找到,返回 false。
更新日志
| 版本 | 说明 |
|---|---|
| 4.3.0 | 该函数是二进制安全的。 |
范例
示例 #1 strrchr 范例
<?php
// 获取 $PATH 中不含磁盘符号的目录
$dir = substr(strrchr($PATH, ":"), 1);
// 获取最后一行内容
$text = "Line 1\nLine 2\nLine 3";
$last = substr(strrchr($text, 10), 1 );
?>
注释
Note: 此函数可安全用于二进制对象。
参见
- strstr
- strrpos
strrev
反转字符串
说明
string strrev
( string
$string )
返回 string 反转后的字符串。
参数
string
待反转的原始字符串。
返回值
返回反转后的字符串。
范例
示例 #1 使用 strrev 反转字符串
<?php
echo strrev("Hello world!"); // 输出 "!dlrow olleH"
?>
strripos
计算指定字符串在目标字符串中最后一次出现的位置(不区分大小写)
说明
int strripos (
string
$haystack , <span
class="type">string $needle [, <span
class="methodparam">int $offset<span
class="initializer"> = 0 ] )
以不区分大小写的方式查找指定字符串在目标字符串中最后一次出现的位置。与 strrpos 不同,<span class="function">strripos 不区分大小写。
参数
haystack
在此字符串中进行查找。
needle
注意 needle 可以是一个单字符或者多字符的字符串。
offset
参数 offset 可以被指定来查找字符串中任意长度的子字符串。
负数偏移量将使得查找从字符串的起始位置开始,到 offset 位置为止。
返回值
返回 needle 相对于 haystack
字符串的位置(和搜索的方向和偏移量无关)。同时注意字符串的起始位置为 0
而非 1。
如果 needle 未被发现,返回 false。
Warning
此函数可能返回布尔值 false,但也可能返回等同于 false
的非布尔值。请阅读
布尔类型章节以获取更多信息。应使用
=== 运算符来测试此函数的返回值。
范例
示例 #1 strripos 简单范例
<?php
$haystack = 'ababcd';
$needle = 'aB';
$pos = strripos($haystack, $needle);
if ($pos === false) {
echo "Sorry, we did not find ($needle) in ($haystack)";
} else {
echo "Congratulations!\n";
echo "We found the last ($needle) in ($haystack) at position ($pos)";
}
?>
以上例程会输出:
Congratulations!
We found the last (aB) in (ababcd) at position (2)
参见
- strpos
- stripos
- strrchr
- substr
- stristr
- strstr
strrpos
计算指定字符串在目标字符串中最后一次出现的位置
说明
int strrpos (
string
$haystack , <span
class="type">string $needle [, <span
class="methodparam">int $offset<span
class="initializer"> = 0 ] )
返回字符串 haystack 中 needle 最后一次出现的数字位置。注意 PHP4
中,needle 只能为单个字符。如果 needle
被指定为一个字符串,那么将仅使用第一个字符。
参数
haystack
在此字符串中进行查找。
needle
如果 needle不是一个字符串,它将被转换为整型并被视为字符的顺序值。
offset
或许会查找字符串中任意长度的子字符串。负数值将导致查找在字符串结尾处开始的计数位置处结束。
返回值
返回 needle 存在的位置。如果没有找到,返回 false。 Also note that
string positions start at 0, and not 1.
Returns false if the needle was not found.
Warning
此函数可能返回布尔值 false,但也可能返回等同于 false
的非布尔值。请阅读
布尔类型章节以获取更多信息。应使用
=== 运算符来测试此函数的返回值。
更新日志
| 版本 | 说明 |
|---|---|
| 5.0.0 | 参数 needle 可以是一个多字符的字符串。 |
| 5.0.0 | 引入 offset 参数。 |
范例
示例 #1 检查字串是否存在
很容易将“在位置 0 处找到”和“未发现字符串”这两种情况搞错。这是检测区别的办法:
<?php
$pos = strrpos($mystring, "b");
if ($pos === false) { // 注意: 三个等号
// 未发现...
}
?>
示例 #2 使用偏移位置进行查找
<?php
$foo = "0123456789a123456789b123456789c";
var_dump(strrpos($foo, '7', -5)); // 从尾部第 5 个位置开始查找
// 结果: int(17)
var_dump(strrpos($foo, '7', 20)); // 从第 20 个位置开始查找
// 结果: int(27)
var_dump(strrpos($foo, '7', 28)); // 结果: bool(false)
?>
参见
- strpos
- stripos
- strripos
- strrchr
- substr
strspn
计算字符串中全部字符都存在于指定字符集合中的第一段子串的长度。
说明
int strspn (
string
$subject , <span
class="type">string $mask [, <span
class="methodparam">int $start [,
int $length
]] )
返回 subject 中全部字符仅存在于 mask
中的第一组连续字符(子字符串)的长度。
如果省略了 start 和 length 参数,则检查整个 subject
字符串;如果指定了这两个参数,则效果等同于调用 strspn(substr($subject,
$start, $length), $mask)(更多信息,参见
)。
代码行:
<?php
$var = strspn("42 is the answer to the 128th question.", "1234567890");
?>
$var 将被指派为 2,因为 '42' 是 subject 中第一段全部字符都存在于
'1234567890' 的连续字符。
参数
subject
待检查的字符串。
mask
检查字符列表。
start
subject 的开始检查位置。
如果 start 被设置并且是非负的,strspn
将从 subject 的第 start 个位置开始检查。例如,在字符串 'abcdef'
中,第 0 个位置的字符是 'a',第二个位置的字符是 'c',等等。
如果 start 被设置并且为负数,strspn 将从
subject 的尾部倒数第 start 个位置开始检查 subject。
length
subject 中检查的长度。
如果 length 被设置并且为非负数,那么将从起始位置开始,检查 subject
的 length 个长度的字符。
如果 length 被设置并且为负数,那么将从起始位置开始,直到从 subject
尾部开始第 length 个位置,对 subject 进行检查。
返回值
返回 str1 中第一段全部字符都存在于 str2 范围的字符串的长度。
更新日志
| 版本 | 说明 |
|---|---|
| 4.3.0 | 新增 start 和 length 参数。 |
范例
示例 #1 strspn 范例
<?php
echo strspn("foo", "o", 1, 2); // 打印: 2
?>
以上例程会输出:
int(0)
int(2)
int(1)
注释
Note: 此函数可安全用于二进制对象。
参见
- strcspn
strstr
查找字符串的首次出现
说明
string strstr
( string
$haystack , <span
class="type">mixed $needle [, <span
class="methodparam">bool $before_needle<span
class="initializer"> = false ] )
返回 haystack 字符串从 needle 第一次出现的位置开始到 haystack
结尾的字符串。
Note:
该函数区分大小写。如果想要不区分大小写,请使用 <span class="function">stristr。
Note:
如果你仅仅想确定
needle是否存在于haystack中,请使用速度更快、耗费内存更少的 <span class="function">strpos 函数。
参数
haystack
输入字符串。
needle
如果 needle
不是一个字符串,那么它将被转化为整型并且作为字符的序号来使用。
before_needle
若为 true,strstr 将返回 needle 在
haystack 中的位置之前的部分。
返回值
返回字符串的一部分或者 false(如果未发现 needle)。
更新日志
| 版本 | 说明 |
|---|---|
| 5.3.0 | 新增可选的 before_needle 参数。 |
| 4.3.0 | strstr 成为二进制安全的。 |
范例
示例 #1 strstr 范例
<?php
$email = '[email protected]';
$domain = strstr($email, '@');
echo $domain; // 打印 @example.com
$user = strstr($email, '@', true); // 从 PHP 5.3.0 起
echo $user; // 打印 name
?>
参见
- preg_match
- stristr
- strpos
- strrchr
- substr
strtok
标记分割字符串
说明
string strtok
( string
$str , <span
class="type">string $token )
string strtok
( string
$token )
strtok 将字符串 str
分割为若干子字符串,每个子字符串以 token
中的字符分割。这也就意味着,如果有个字符串是 "This is an example
string",你可以使用空格字符将这句话分割成独立的单词。
注意仅第一次调用 strtok 函数时使用 string 参数。后来每次调用 strtok,都将只使用 token 参数,因为它会记住它在字符串 string 中的位置。如果要重新开始分割一个新的字符串,你需要再次使用 string 来调用 strtok 函数,以便完成初始化工作。注意可以在 token 参数中使用多个字符。字符串将被该参数中任何一个字符分割。
参数
str
被分成若干子字符串的原始字符串。
token
分割 str 时使用的分界字符。
返回值
标记后的字符串。
范例
示例 #1 strtok 范例
<?php
$string = "This is\tan example\nstring";
/* 使用制表符和换行符作为分界符 */
$tok = strtok($string, " \n\t");
while ($tok !== false) {
echo "Word=$tok<br />";
$tok = strtok(" \n\t");
}
?>
示例 #2 当存在空的部分时 strtok 的反应
<?php
$first_token = strtok('/something', '/');
$second_token = strtok('/');
var_dump($first_token, $second_token);
?>
以上例程会输出:
string(9) "something"
bool(false)
注释
Warning
此函数可能返回布尔值 false,但也可能返回等同于 false
的非布尔值。请阅读
布尔类型章节以获取更多信息。应使用
=== 运算符来测试此函数的返回值。
参见
- split
- explode
strtolower
将字符串转化为小写
说明
string <span
class="methodname">strtolower ( <span
class="type">string $string )
将 string 中所有的字母字符转换为小写并返回。
注意 “字母” 与当前所在区域有关。例如,在默认的 “C” 区域,字符 umlaut-A(ä)就不会被转换。
参数
string
输入字符串。
返回值
返回转换后的小写字符串。
范例
示例 #1 strtolower 范例
<?php
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = strtolower($str);
echo $str; // 打印 mary had a little lamb and she loved it so
?>
注释
Note: 此函数可安全用于二进制对象。
参见
- strtoupper
- ucfirst
- ucwords
- mb_strtolower
strtoupper
将字符串转化为大写
说明
string <span
class="methodname">strtoupper ( <span
class="type">string $string )
将 string 中所有的字母字符转换为大写并返回。
注意 “字母” 与当前所在区域有关。例如,在默认的 “C” 区域,字符 umlaut-a(ä)就不会被转换。
参数
string
输入字符串。
返回值
返回转换后的大写字符串。
范例
示例 #1 strtoupper 范例
<?php
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = strtoupper($str);
echo $str; // 打印 MARY HAD A LITTLE LAMB AND SHE LOVED IT SO
?>
注释
Note: 此函数可安全用于二进制对象。
参见
- strtolower
- ucfirst
- ucwords
- mb_strtoupper
strtr
转换指定字符
说明
string strtr (
string $str
, string
$from , <span
class="type">string $to )
string strtr (
string $str
, array
$replace_pairs )
该函数返回 str 的一个副本,并将在 from 中指定的字符转换为 to
中相应的字符。 比如, $from[$n]中每次的出现都会被替换为
$to[$n],其中 $n 是两个参数都有效的位移(offset)。
如果 from 与 to 长度不相等,那么多余的字符部分将被忽略。 str
的长度将会和返回的值一样。
If given two arguments, the second should be an <span class="type">array in the form array('from' => 'to', ...). The return value is a string where all the occurrences of the array keys have been replaced by the corresponding values. The longest keys will be tried first. Once a substring has been replaced, its new value will not be searched again.
In this case, the keys and the values may have any length, provided that
there is no empty key; additionally, the length of the return value may
differ from that of str. However, this function will be the most
efficient when all the keys have the same size.
参数
str
待转换的字符串。
from
字符串中与将要被转换的目的字符 to
相对应的源字符。
to
字符串中与将要被转换的字符 from
相对应的目的字符。
replace_pairs
参数 replace_pairs 可以用来取代 to 和 from 参数,因为它是以
array('from' => 'to', ...) 格式出现的数组。
返回值
返回转换后的字符串。
如果 replace_pairs 中包含一个空<span
class="type">字符串("")键,那么将返回 false。 If the
str is not a scalar then it is not typecasted into a string, instead a
warning is raised and null is returned.
范例
示例 #1 strtr 范例
<?php
$addr = strtr($addr, "äåö", "aao");
?>
The next example shows the behavior of <span class="function">strtr when called with only two arguments. Note the preference of the replacements ("h" is not picked because there are longer matches) and how replaced text was not searched again.
示例 #2 使用两个参数的 strtr 范例
<?php
$trans = array("hello" => "hi", "hi" => "hello");
echo strtr("hi all, I said hello", $trans);
?>
以上例程会输出:
hello all, I said hi
The two modes of behavior are substantially different. With three arguments, strtr will replace bytes; with two, it may replace longer substrings.
示例 #3 strtr behavior comparison
<?php
echo strtr("baab", "ab", "01"),"\n";
$trans = array("ab" => "01");
echo strtr("baab", $trans);
?>
以上例程会输出:
1001
ba01
参见
- str_replace
- preg_replace
substr_compare
二进制安全比较字符串(从偏移位置比较指定长度)
说明
int <span
class="methodname">substr_compare ( <span
class="methodparam">string $main_str
, string
$str , int
$offset [, <span
class="type">int $length [, <span
class="methodparam">bool
$case_insensitivity =
false ]] )
substr_compare 从偏移位置 offset
开始比较 main_str 与 str,比较长度为 length 个字符。
参数
main_str
待比较的第一个字符串。
str
待比较的第二个字符串。
offset
比较开始的位置。如果为负数,则从字符串结尾处开始算起。
length
比较的长度。默认值为 str 的长度与 main_str 的长度减去位置偏移量
offset 后二者中的较大者。
case_insensitivity
如果 case_insensitivity 为 true,比较将不区分大小写。
返回值
如果 main_str 从偏移位置 offset 起的子字符串小于 str,则返回小于 0
的数;如果大于 str,则返回大于 0 的数;如果二者相等,则返回 0。如果
offset 大于等于 main_str 的长度或 length 被设置为小于 1 的值( PHP
5.5.11 之前的版本),substr_compare
将打印出一条警告信息并且返回 false。
更新日志
| 版本 | 说明 |
|---|---|
| 7.2.18, 7.3.5 | offset 现在可能等于 main_str。 |
范例
示例 #1 substr_compare 范例
<?php
echo substr_compare("abcde", "bc", 1, 2); // 0
echo substr_compare("abcde", "de", -2, 2); // 0
echo substr_compare("abcde", "bcg", 1, 2); // 0
echo substr_compare("abcde", "BC", 1, 2, true); // 0
echo substr_compare("abcde", "bc", 1, 3); // 1
echo substr_compare("abcde", "cd", 1, 2); // -1
echo substr_compare("abcde", "abc", 5, 1); // warning
?>
参见
- strncmp
substr_count
计算字串出现的次数
说明
int <span
class="methodname">substr_count ( <span
class="methodparam">string $haystack
, string
$needle [, <span
class="type">int $offset =
0 [, <span
class="type">int $length ]] )
substr_count 返回子字符串 needle
在字符串 haystack 中出现的次数。注意 needle 区分大小写。
Note:
该函数不会计算重叠字符串!参见下面的例子。
参数
haystack
在此字符串中进行搜索。
needle
要搜索的字符串。
offset
开始计数的偏移位置。如果是负数,就从字符的末尾开始统计。
length
指定偏移位置之后的最大搜索长度。如果偏移量加上这个长度的和大于
haystack 的总长度,则打印警告信息。 负数的长度 length 是从 haystack
的末尾开始统计的。
返回值
该函数返回 整型。
更新日志
| 版本 | 说明 |
|---|---|
| 7.1.0 | 开始支持负数的 offset 和 length。 |
范例
示例 #1 substr_count 范例
<?php
$text = 'This is a test';
echo strlen($text); // 14
echo substr_count($text, 'is'); // 2
// 字符串被简化为 's is a test',因此输出 1
echo substr_count($text, 'is', 3);
// 字符串被简化为 's i',所以输出 0
echo substr_count($text, 'is', 3, 3);
// 因为 5+10 > 14,所以生成警告
echo substr_count($text, 'is', 5, 10);
// 输出 1,因为该函数不计算重叠字符串
$text2 = 'gcdgcdgcd';
echo substr_count($text2, 'gcdgcd');
?>
参见
- count_chars
- strpos
- substr
- strstr
substr_replace
替换字符串的子串
说明
mixed <span
class="methodname">substr_replace ( <span
class="methodparam">mixed $string ,
mixed
$replacement , <span
class="type">mixed $start [, <span
class="methodparam">mixed $length ]
)
substr_replace 在字符串 string
的副本中将由 start 和可选的 length 参数限定的子字符串使用
replacement 进行替换。
参数
string
输入字符串。
An array of strings
can be provided, in which case the replacements will occur on each
string in turn. In this case, the replacement, start and length
parameters may be provided either as scalar values to be applied to each
input string in turn, or as arrays, in which
case the corresponding array element will be used for each input string.
replacement
替换字符串。
start
如果 start 为正数,替换将从 string 的 start 位置开始。
如果 start 为负数,替换将从 string 的倒数第 start 个位置开始。
length
如果设定了这个参数并且为正数,表示 string
中被替换的子字符串的长度。如果设定为负数,它表示待替换的子字符串结尾处距离
string 末端的字符个数。如果没有提供此参数,那么它默认为 strlen(
string ) (字符串的长度)。当然,如果 length 为
0,那么这个函数的功能为将 replacement 插入到 string 的 start
位置处。
返回值
返回结果字符串。如果 string 是个数组,那么也将返回一个数组。
更新日志
| 版本 | 说明 |
|---|---|
| 4.3.3 | All parameters now accept arrays. |
范例
示例 #1 substr_replace 范例
<?php
$var = 'ABCDEFGH:/MNRPQR/';
echo "Original: $var<hr />\n";
/* 这两个例子使用 “bob” 替换整个 $var。*/
echo substr_replace($var, 'bob', 0) . "<br />\n";
echo substr_replace($var, 'bob', 0, strlen($var)) . "<br />\n";
/* 将 “bob” 插入到 $var 的开头处。*/
echo substr_replace($var, 'bob', 0, 0) . "<br />\n";
/* 下面两个例子使用 “bob” 替换 $var 中的 “MNRPQR”。*/
echo substr_replace($var, 'bob', 10, -1) . "<br />\n";
echo substr_replace($var, 'bob', -7, -1) . "<br />\n";
/* 从 $var 中删除 “MNRPQR”。*/
echo substr_replace($var, '', 10, -1) . "<br />\n";
?>
示例 #2 Using substr_replace to replace multiple strings at once
<?php
$input = array('A: XXX', 'B: XXX', 'C: XXX');
// A simple case: replace XXX in each string with YYY.
echo implode('; ', substr_replace($input, 'YYY', 3, 3))."\n";
// A more complicated case where each replacement is different.
$replace = array('AAA', 'BBB', 'CCC');
echo implode('; ', substr_replace($input, $replace, 3, 3))."\n";
// Replace a different number of characters each time.
$length = array(1, 2, 3);
echo implode('; ', substr_replace($input, $replace, 3, $length))."\n";
?>
以上例程会输出:
A: YYY; B: YYY; C: YYY
A: AAA; B: BBB; C: CCC
A: AAAXX; B: BBBX; C: CCC
注释
Note: 此函数可安全用于二进制对象。
参见
- str_replace
- substr
- 字符串访问与修改
substr
返回字符串的子串
说明
string substr
( string
$string , <span
class="type">int $start [, <span
class="methodparam">int $length ] )
返回字符串 string 由 start 和 length 参数指定的子字符串。
参数
string
输入字符串。必须至少有一个字符。
start
如果 start 是非负数,返回的字符串将从 string 的 start 位置开始,从
0 开始计算。例如,在字符串 “abcdef” 中,在位置 0 的字符是
“a”,位置 2 的字符串是 “c” 等等。
如果 start 是负数,返回的字符串将从 string 结尾处向前数第 start
个字符开始。
如果 string 的长度小于 start,将返回 false。
示例 #1 使用负数 start
<?php
$rest = substr("abcdef", -1); // 返回 "f"
$rest = substr("abcdef", -2); // 返回 "ef"
$rest = substr("abcdef", -3, 1); // 返回 "d"
?>
length
如果提供了正数的 length,返回的字符串将从 start 处开始最多包括
length 个字符(取决于 string 的长度)。
如果提供了负数的 length,那么 string 末尾处的 length
个字符将会被省略(若 start 是负数则从字符串尾部算起)。如果 start
不在这段文本中,那么将返回 false。
如果提供了值为 0,false 或 null 的
length,那么将返回一个空字符串。
如果没有提供 length,返回的子字符串将从 start
位置开始直到字符串结尾。
示例 #2 使用负数 length
<?php
$rest = substr("abcdef", 0, -1); // 返回 "abcde"
$rest = substr("abcdef", 2, -1); // 返回 "cde"
$rest = substr("abcdef", 4, -4); // 返回 ""
$rest = substr("abcdef", -3, -1); // 返回 "de"
?>
返回值
返回提取的子字符串, 或者在失败时返回 false。
更新日志
| 版本 | 说明 |
|---|---|
| 7.0.0 | 如果 string 的字符串长度与 start 相同时将返回一个空字符串。在之前的版本中,这种情况将返回 false 。 |
| 5.2.2 - 5.2.6 | If the start parameter indicates the position of a negative truncation or beyond, false is returned. Other versions get the string from start. |
范例
示例 #3 substr 基本用法
<?php
echo substr('abcdef', 1); // bcdef
echo substr('abcdef', 1, 3); // bcd
echo substr('abcdef', 0, 4); // abcd
echo substr('abcdef', 0, 8); // abcdef
echo substr('abcdef', -1, 1); // f
// 访问字符串中的单个字符
// 也可以使用中括号
$string = 'abcdef';
echo $string[0]; // a
echo $string[3]; // d
echo $string[strlen($string)-1]; // f
?>
示例 #4 substr casting behaviour
<?php
class apple {
public function __toString() {
return "green";
}
}
echo "1) ".var_export(substr("pear", 0, 2), true).PHP_EOL;
echo "2) ".var_export(substr(54321, 0, 2), true).PHP_EOL;
echo "3) ".var_export(substr(new apple(), 0, 2), true).PHP_EOL;
echo "4) ".var_export(substr(true, 0, 1), true).PHP_EOL;
echo "5) ".var_export(substr(false, 0, 1), true).PHP_EOL;
echo "6) ".var_export(substr("", 0, 1), true).PHP_EOL;
echo "7) ".var_export(substr(1.2e3, 0, 4), true).PHP_EOL;
?>
以上例程在 PHP 7 中的输出:
1) 'pe'
2) '54'
3) 'gr'
4) '1'
5) false
6) false
7) '1200'
以上例程在 PHP 5 中的输出:
1) 'pe'
2) '54'
3) 'gr'
4) '1'
5) false
6) false
7) '1200'
错误/异常
错误时返回 false。
<?php
var_dump(substr('a', 2)); // bool(false)
?>
参见
- strrchr
- substr_replace
- preg_match
- trim
- mb_substr
- wordwrap
- 字符串访问和修改
trim
去除字符串首尾处的空白字符(或者其他字符)
说明
string trim (
string $str
[, string
$character_mask = "
\t\n\r\0\x0B" ] )
此函数返回字符串 str
去除首尾空白字符后的结果。如果不指定第二个参数,<span
class="function">trim 将去除这些字符:
- " " (ASCII 32 (0x20)),普通空格符。
- "\t" (ASCII 9 (0x09)),制表符。
- "\n" (ASCII 10 (0x0A)),换行符。
- "\r" (ASCII 13 (0x0D)),回车符。
- "\0" (ASCII 0 (0x00)),空字节符。
- "\x0B" (ASCII 11 (0x0B)),垂直制表符。
参数
str
待处理的字符串。
character_mask
可选参数,过滤字符也可由 character_mask
参数指定。一般要列出所有希望过滤的字符,也可以使用 “..”
列出一个字符范围。
返回值
过滤后的字符串。
范例
示例 #1 trim 使用范例
<?php
$text = "\t\tThese are a few words :) ... ";
$binary = "\x09Example string\x0A";
$hello = "Hello World";
var_dump($text, $binary, $hello);
print "\n";
$trimmed = trim($text);
var_dump($trimmed);
$trimmed = trim($text, " \t.");
var_dump($trimmed);
$trimmed = trim($hello, "Hdle");
var_dump($trimmed);
// 清除 $binary 首位的 ASCII 控制字符
// (包括 0-31)
$clean = trim($binary, "\x00..\x1F");
var_dump($clean);
?>
以上例程会输出:
string(32) " These are a few words :) ... "
string(16) " Example string
"
string(11) "Hello World"
string(28) "These are a few words :) ..."
string(24) "These are a few words :)"
string(5) "o Wor"
string(14) "Example string"
示例 #2 使用 trim 清理数组值
<?php
function trim_value(&$value)
{
$value = trim($value);
}
$fruit = array('apple','banana ', ' cranberry ');
var_dump($fruit);
array_walk($fruit, 'trim_value');
var_dump($fruit);
?>
以上例程会输出:
array(3) {
[0]=>
string(5) "apple"
[1]=>
string(7) "banana "
[2]=>
string(11) " cranberry "
}
array(3) {
[0]=>
string(5) "apple"
[1]=>
string(6) "banana"
[2]=>
string(9) "cranberry"
}
注释
Note: Possible gotcha: removing middle characters
Because trim trims characters from the beginning and end of a string, it may be confusing when characters are (or are not) removed from the middle. trim('abc', 'bad') removes both 'a' and 'b' because it trims 'a' thus moving 'b' to the beginning to also be trimmed. So, this is why it "works" whereas trim('abc', 'b') seemingly does not.
参见
- ltrim
- rtrim
- str_replace
ucfirst
将字符串的首字母转换为大写
说明
string ucfirst
( string
$str )
将 str 的首字符(如果首字符是字母)转换为大写字母,并返回这个字符串。
注意字母的定义取决于当前区域设定。例如,在默认的 “C” 区域,字符 umlaut-a(ä)将不会被转换。
参数
str
输入字符串。
返回值
返回结果字符串。
范例
示例 #1 ucfirst 范例
<?php
$foo = 'hello world!';
$foo = ucfirst($foo); // Hello world!
$bar = 'HELLO WORLD!';
$bar = ucfirst($bar); // HELLO WORLD!
$bar = ucfirst(strtolower($bar)); // Hello world!
?>
参见
- lcfirst
- strtolower
- strtoupper
- ucwords
ucwords
将字符串中每个单词的首字母转换为大写
说明
string ucwords
( string
$str [, <span
class="type">string $delimiters = "
\t\r\n\f\v" ] )
将 str
中每个单词的首字符(如果首字符是字母)转换为大写字母,并返回这个字符串。
这里单词的定义是紧跟在 delimiters
参数(默认:空格符、制表符、换行符、回车符、水平线以及竖线)之后的子字符串。
参数
str
输入字符串。
delimiters
可选的 delimiters,包含了单词分割字符。
返回值
返回转换后的字符串。
更新日志
| 版本 | 说明 |
|---|---|
| 5.4.32, 5.5.16 | 增加了 delimiters 参数。 |
范例
示例 #1 ucwords 范例
<?php
$foo = 'hello world!';
$foo = ucwords($foo); // Hello World!
$bar = 'HELLO WORLD!';
$bar = ucwords($bar); // HELLO WORLD!
$bar = ucwords(strtolower($bar)); // Hello World!
?>
示例 #2 ucwords 自定义 delimiters 的例子
<?php
$foo = 'hello|world!';
$bar = ucwords($foo); // Hello|world!
$baz = ucwords($foo, "|"); // Hello|World!
?>
注释
Note: 此函数可安全用于二进制对象。
参见
- strtoupper
- strtolower
- ucfirst
- mb_convert_case
vfprintf
将格式化字符串写入流
说明
int vfprintf (
resource
$handle , <span
class="type">string $format , <span
class="methodparam">array $args )
向由 handle 指定的流资源句柄中写入根据 format 格式化后的字符串。
作用与 fprintf 函数类似,但是接收一个数组参数,而不是一系列可变数量的参数。
参数
handle
format
关于 format 的描述,参见 sprintf。
args
返回值
返回输出字符串的长度。
范例
示例 #1 vfprintf: 前导 0 的整数
<?php
if (!($fp = fopen('date.txt', 'w')))
return;
vfprintf($fp, "%04d-%02d-%02d", array($year, $month, $day));
// 将向 date.txt 写入格式化的 ISO 标准日期
?>
参见
- printf
- sprintf
- sscanf
- fscanf
- vsprintf
- number_format
vprintf
输出格式化字符串
说明
int vprintf (
string
$format , <span
class="type">array $args )
根据 format (sprintf
函数文档中有相关描述)参数指定的格式,在一个格式化字符串中显示多个值。
作用与 printf 函数类似,但是接收一个数组参数,而不是一系列可变数量的参数。
参数
format
关于 format 的描述,参见 sprintf。
args
返回值
返回输出字符串的长度。
范例
示例 #1 vprintf: 前导 0 的整数
<?php
vprintf("%04d-%02d-%02d", explode('-', '1988-8-1')); // 1988-08-01
?>
参见
- printf
- sprintf
- vsprintf
vsprintf
返回格式化字符串
说明
string <span
class="methodname">vsprintf ( <span
class="type">string $format , <span
class="methodparam">array $args )
作用与 sprintf 函数类似,但是接收一个数组参数,而不是一系列可变数量的参数。
参数
format
The format string is composed of zero or more directives: ordinary
characters (excluding %) that are copied directly to the result and
conversion specifications, each of which results in fetching its own
parameter.
A conversion specification follows this prototype: %[argnum$][flags][width][.precision]specifier.
Argnum
An integer followed by a dollar sign $, to specify which number argument to treat in the conversion.
| Flag | 说明 |
|---|---|
| - | Left-justify within the given field width; Right justification is the default |
| + | Prefix positive numbers with a plus sign +; Default only negative are prefixed with a negative sign. |
| (space) | Pads the result with spaces. This is the default. |
| 0 | Only left-pads numbers with zeros. With s specifiers this can also right-pad with zeros. |
| '(char) | Pads the result with the character (char). |
Width
An integer that says how many characters (minimum) this conversion should result in.
Precision
A period . followed by an integer who's meaning depends on the specifier:
- For e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6).
- For g and G specifiers: this is the maximum number of significant digits to be printed.
- For s specifier: it acts as a cutoff point, setting a maximum character limit to the string.
Note: If the period is specified without an explicit value for precision, 0 is assumed.
Note: Attempting to use a position specifier greater than
PHP_INT_MAXwill generate warnings.
| Specifier | 说明 |
|---|---|
| % | A literal percent character. No argument is required. |
| b | The argument is treated as an integer and presented as a binary number. |
| c | The argument is treated as an integer and presented as the character with that ASCII. |
| d | The argument is treated as an integer and presented as a (signed) decimal number. |
| e | The argument is treated as scientific notation (e.g. 1.2e+2). The precision specifier stands for the number of digits after the decimal point since PHP 5.2.1. In earlier versions, it was taken as number of significant digits (one less). |
| E | Like the e specifier but uses uppercase letter (e.g. 1.2E+2). |
| f | The argument is treated as a float and presented as a floating-point number (locale aware). |
| F | The argument is treated as a float and presented as a floating-point number (non-locale aware). Available as of PHP 5.0.3. |
| g | General format. Let P equal the precision if nonzero, 6 if the precision is omitted, or 1 if the precision is zero. Then, if a conversion with style E would have an exponent of X: If P > X ≥ −4, the conversion is with style f and precision P − (X + 1). Otherwise, the conversion is with style e and precision P − 1. |
| G | Like the g specifier but uses E and f. |
| o | The argument is treated as an integer and presented as an octal number. |
| s | The argument is treated and presented as a string. |
| u | The argument is treated as an integer and presented as an unsigned decimal number. |
| x | The argument is treated as an integer and presented as a hexadecimal number (with lowercase letters). |
| X | The argument is treated as an integer and presented as a hexadecimal number (with uppercase letters). |
Warning The c type specifier ignores padding and width
Warning Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results
Variables will be co-erced to a suitable type for the specifier:
| Type | Specifiers |
|---|---|
| string | s |
| integer | d, u, c, o, x, X, b |
| double | g, G, e, E, f, F |
args
返回值
根据 format 参数指定的格式,在一个字符串中返回一系列值,
或者在失败时返回 false。
范例
示例 #1 vsprintf: 前导 0 的整数
<?php
print vsprintf("%04d-%02d-%02d", explode('-', '1988-8-1'));
?>
以上例程会输出:
1988-08-01
参见
- printf
- sprintf
- fprintf
- vprintf
- vfprintf
- sscanf
- fscanf
- number_format
- date
wordwrap
打断字符串为指定数量的字串
说明
string <span
class="methodname">wordwrap ( <span
class="type">string $str [, <span
class="methodparam">int $width<span
class="initializer"> = 75 [, <span
class="methodparam">string $break<span
class="initializer"> = "\n" [, <span
class="methodparam">bool $cut<span
class="initializer"> = false ]]] )
使用字符串断点将字符串打断为指定数量的字串。
参数
str
输入字符串。
width
列宽度。
break
使用可选的 break 参数打断字符串。
cut
如果 cut 设置为 true,字符串总是在指定的 width
或者之前位置被打断。因此,如果有的单词宽度超过了给定的宽度,它将被分隔开来。(参见第二个范例)。
当它是 false ,函数不会分割单词,哪怕 width 小于单词宽度。
返回值
返回打断后的字符串。
范例
示例 #1 wordwrap 范例
<?php
$text = "The quick brown fox jumped over the lazy dog.";
$newtext = wordwrap($text, 20, "<br />\n");
echo $newtext;
?>
以上例程会输出:
The quick brown fox<br />
jumped over the lazy<br />
dog.
示例 #2 wordwrap 范例
<?php
$text = "A very long woooooooooooord.";
$newtext = wordwrap($text, 8, "\n", true);
echo "$newtext\n";
?>
以上例程会输出:
A very
long
wooooooo
ooooord.
示例 #3 wordwrap 例子
<?php
$text = "A very long woooooooooooooooooord. and something";
$newtext = wordwrap($text, 8, "\n", false);
echo "$newtext\n";
?>
以上例程会输出:
A very
long
woooooooooooooooooord.
and
something
参见
- nl2br
- chunk_split
目录
- addcslashes — 以 C 语言风格使用反斜线转义字符串中的字符
- addslashes — 使用反斜线引用字符串
- bin2hex — 函数把包含数据的二进制字符串转换为十六进制值
- chop — rtrim 的别名
- chr — 返回指定的字符
- chunk_split — 将字符串分割成小块
- convert_cyr_string — 将字符由一种 Cyrillic 字符转换成另一种
- convert_uudecode — 解码一个 uuencode 编码的字符串
- convert_uuencode — 使用 uuencode 编码一个字符串
- count_chars — 返回字符串所用字符的信息
- crc32 — 计算一个字符串的 crc32 多项式
- crypt — 单向字符串散列
- echo — 输出一个或多个字符串
- explode — 使用一个字符串分割另一个字符串
- fprintf — 将格式化后的字符串写入到流
- get_html_translation_table — 返回使用 htmlspecialchars 和 htmlentities 后的转换表
- hebrev — 将逻辑顺序希伯来文(logical-Hebrew)转换为视觉顺序希伯来文(visual-Hebrew)
- hebrevc — 将逻辑顺序希伯来文(logical-Hebrew)转换为视觉顺序希伯来文(visual-Hebrew),并且转换换行符
- hex2bin — 转换十六进制字符串为二进制字符串
- html_entity_decode — Convert HTML entities to their corresponding characters
- htmlentities — 将字符转换为 HTML 转义字符
- htmlspecialchars_decode — 将特殊的 HTML 实体转换回普通字符
- htmlspecialchars — 将特殊字符转换为 HTML 实体
- implode — 将一个一维数组的值转化为字符串
- join — 别名 implode
- lcfirst — 使一个字符串的第一个字符小写
- levenshtein — 计算两个字符串之间的编辑距离
- localeconv — Get numeric formatting information
- ltrim — 删除字符串开头的空白字符(或其他字符)
- md5_file — 计算指定文件的 MD5 散列值
- md5 — 计算字符串的 MD5 散列值
- metaphone — Calculate the metaphone key of a string
- money_format — 将数字格式化成货币字符串
- nl_langinfo — Query language and locale information
- nl2br — 在字符串所有新行之前插入 HTML 换行标记
- number_format — 以千位分隔符方式格式化一个数字
- ord — 转换字符串第一个字节为 0-255 之间的值
- parse_str — 将字符串解析成多个变量
- print — 输出字符串
- printf — 输出格式化字符串
- quoted_printable_decode — 将 quoted-printable 字符串转换为 8-bit 字符串
- quoted_printable_encode — 将 8-bit 字符串转换成 quoted-printable 字符串
- quotemeta — 转义元字符集
- rtrim — 删除字符串末端的空白字符(或者其他字符)
- setlocale — 设置地区信息
- sha1_file — 计算文件的 sha1 散列值
- sha1 — 计算字符串的 sha1 散列值
- similar_text — 计算两个字符串的相似度
- soundex — Calculate the soundex key of a string
- sprintf — Return a formatted string
- sscanf — 根据指定格式解析输入的字符
- str_contains — Determine if a string contains a given substring
- str_ends_with — Checks if a string ends with a given substring
- str_getcsv — 解析 CSV 字符串为一个数组
- str_ireplace — str_replace 的忽略大小写版本
- str_pad — 使用另一个字符串填充字符串为指定长度
- str_repeat — 重复一个字符串
- str_replace — 子字符串替换
- str_rot13 — 对字符串执行 ROT13 转换
- str_shuffle — 随机打乱一个字符串
- str_split — 将字符串转换为数组
- str_starts_with — Checks if a string starts with a given substring
- str_word_count — 返回字符串中单词的使用情况
- strcasecmp — 二进制安全比较字符串(不区分大小写)
- strchr — 别名 strstr
- strcmp — 二进制安全字符串比较
- strcoll — 基于区域设置的字符串比较
- strcspn — 获取不匹配遮罩的起始子字符串的长度
- strip_tags — 从字符串中去除 HTML 和 PHP 标记
- stripcslashes — 反引用一个使用 addcslashes 转义的字符串
- stripos — 查找字符串首次出现的位置(不区分大小写)
- stripslashes — 反引用一个引用字符串
- stristr — strstr 函数的忽略大小写版本
- strlen — 获取字符串长度
- strnatcasecmp — 使用“自然顺序”算法比较字符串(不区分大小写)
- strnatcmp — 使用自然排序算法比较字符串
- strncasecmp — 二进制安全比较字符串开头的若干个字符(不区分大小写)
- strncmp — 二进制安全比较字符串开头的若干个字符
- strpbrk — 在字符串中查找一组字符的任何一个字符
- strpos — 查找字符串首次出现的位置
- strrchr — 查找指定字符在字符串中的最后一次出现
- strrev — 反转字符串
- strripos — 计算指定字符串在目标字符串中最后一次出现的位置(不区分大小写)
- strrpos — 计算指定字符串在目标字符串中最后一次出现的位置
- strspn — 计算字符串中全部字符都存在于指定字符集合中的第一段子串的长度。
- strstr — 查找字符串的首次出现
- strtok — 标记分割字符串
- strtolower — 将字符串转化为小写
- strtoupper — 将字符串转化为大写
- strtr — 转换指定字符
- substr_compare — 二进制安全比较字符串(从偏移位置比较指定长度)
- substr_count — 计算字串出现的次数
- substr_replace — 替换字符串的子串
- substr — 返回字符串的子串
- trim — 去除字符串首尾处的空白字符(或者其他字符)
- ucfirst — 将字符串的首字母转换为大写
- ucwords — 将字符串中每个单词的首字母转换为大写
- vfprintf — 将格式化字符串写入流
- vprintf — 输出格式化字符串
- vsprintf — 返回格式化字符串
- wordwrap — 打断字符串为指定数量的字串