PHP 字符串常用函数

409 阅读5分钟

addslashes

(PHP 4, PHP 5, PHP 7)

使用反斜线引用字符串

说明

addslashes ( string $str ) : string

返回字符串,该字符串为了数据库查询语句等的需要在某些字符前加上了反斜线。这些字符是单引号(')、双引号(")、反斜线(\)与 NUL(NULL 字符)。

参数

str

要转义的字符。

返回值

返回转义后的字符。

范例

Example 1 一个 addslashes() 例子

<?php
$str = "Is your name O'reilly?";

// 输出: Is your name O\'reilly?
echo addslashes($str);
?>

stripslashes

(PHP 4, PHP 5, PHP 7)

反引用一个引用字符串

说明

stripslashes ( string $str ) : string

反引用一个引用字符串。

参数

str

输入字符串。

返回值

返回一个去除转义反斜线后的字符串(' 转换为 ' 等等)。双反斜线(\)被转换为单个反斜线(\)。

范例

Example 1 stripslashes() 范例

<?php
$str = "Is your name O\'reilly?";

// 输出: Is your name O'reilly?
echo stripslashes($str);
?>

echo

(PHP 4, PHP 5, PHP 7)

输出一个或多个字符串

说明

echo ( string $arg1 [, string $... ] ) : void

输出所有参数。不会换行。

echo 不是一个函数(它是一个语言结构), 因此你不一定要使用小括号来指明参数,单引号,双引号都可以。 echo (不像其他语言构造)不表现得像一个函数, 所以不能总是使用一个函数的上下文。 另外,如果你想给 echo 传递多个参数, 那么就不能使用小括号。

echo 也有一个快捷用法,你可以在打开标记前直接用一个等号。在 PHP 5.4.0 之前,必须在php.ini 里面启用 short_open_tag 才有效。

I have foo. 和 print 最主要的不同之处是, echo 接受参数列表,并且没有返回值。

参数

arg1

要输出的参数

...

返回值

没有返回值。

范例

Example 1 echo 例子

<?php
echo "Hello World";

echo "This spans
multiple lines. The newlines will be
output as well";

echo "This spans\nmultiple lines. The newlines will be\noutput as well.";

echo "Escaping characters is done \"Like this\".";

// You can use variables inside of an echo statement
$foo = "foobar";
$bar = "barbaz";

echo "foo is $foo"; // foo is foobar

// You can also use arrays
$baz = array("value" => "foo");

echo "this is {$baz['value']} !"; // this is foo !

// Using single quotes will print the variable name, not the value
echo 'foo is $foo'; // foo is $foo

// If you are not using any other characters, you can just echo variables
echo $foo;          // foobar
echo $foo,$bar;     // foobarbarbaz

// 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";

echo <<<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;

// 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
?>

explode

(PHP 4, PHP 5, PHP 7)

使用一个字符串分割另一个字符串

说明

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

此函数返回由字符串组成的数组,每个元素都是 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 , 那么会返回空的 array, 否则返回包含 string 单个元素的数组。

范例

Example 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; // *

?>

Example 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"
)

Example 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
)

implode

(PHP 4, PHP 5, PHP 7)

将一个一维数组的值转化为字符串

说明

implode ( string $glue , array $pieces ) : string

implode ( array $pieces ) : string

glue 将一维数组的值连接为一个字符串。

Note:

因为历史原因,implode() 可以接收两种参数顺序,但是 explode() 不行。不过按文档中的顺序可以避免混淆。

参数

glue

默认为空的字符串。

pieces

你想要转换的数组。

返回值

返回一个字符串,其内容为由 glue 分割开的数组的值。

范例

Example 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) ""

?>

lcfirst

(PHP 5 >= 5.3.0, PHP 7)

使一个字符串的第一个字符小写

说明

lcfirst ( string $str ) : string

返回第一个字母小写的 str ,如果是字母的话。

参数

str

输入的字符串。

返回值

返回转换后的字符串。

范例

Example 1 lcfirst() 例子:

<?php
$foo = 'HelloWorld';
$foo = lcfirst($foo);             // helloWorld

$bar = 'HELLO WORLD!';
$bar = lcfirst($bar);             // hELLO WORLD!
$bar = lcfirst(strtoupper($bar)); // hELLO WORLD!
?>

ltrim

(PHP 4, PHP 5, PHP 7)

删除字符串开头的空白字符(或其他字符)

说明

ltrim ( string $str [, string $character_mask ] ) : string

删除字符串开头的空白字符(或其他字符)

参数

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)),垂直制表符。

范例

Example 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
"

rtrim

(PHP 4, PHP 5, PHP 7)

删除字符串末端的空白字符(或者其他字符)

说明

rtrim ( string $str [, string $character_mask ] ) : string

该函数删除 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,可以指定想要删除的字符列表。简单地列出你想要删除的全部字符。使用 .. 格式,可以指定一个范围。

返回值

返回改变后的字符串。

范例

Example 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"

str_replace

(PHP 4, PHP 5, PHP 7)

子字符串替换

说明

str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] ) : mixed

该函数返回一个字符串或者数组。该字符串或数组是将 subject 中全部的 search 都被 replace 替换之后的结果。

如果没有一些特殊的替换需求(比如正则表达式),你应该使用该函数替换 ereg_replace()preg_replace()

参数

如果 searchreplace 为数组,那么 str_replace() 将对 subject 做二者的映射替换。如果 replace 的值的个数少于 search 的个数,多余的替换将使用空字符串来进行。如果 search 是一个数组而 replace 是一个字符串,那么 search 中每个元素的替换将始终使用这个字符串。该转换不会改变大小写。

如果 searchreplace 都是数组,它们的值将会被依次处理。

search

查找的目标值,也就是 needle。一个数组可以指定多个目标。

replace

search 的替换值。一个数组可以被用来指定多重替换。

subject

执行替换的数组或者字符串。也就是 haystack

如果 subject 是一个数组,替换操作将遍历整个 subject,返回值也将是一个数组。

count

如果被指定,它的值将被设置为替换发生的次数。

返回值

该函数返回替换后的数组或者字符串。

范例

Example 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;
?>

Example 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;
?>

str_split

(PHP 5, PHP 7)

将字符串转换为数组

说明

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

将一个字符串转换为数组。

参数

string

输入字符串。

split_length

每一段的长度。

返回值

如果指定了可选的 split_length 参数,返回数组中的每个元素均为一个长度为 split_length 的字符块,否则每个字符块为单个字符。

如果 split_length 小于 1,返回 FALSE。如果 split_length 参数超过了 string 超过了字符串 string 的长度,整个字符串将作为数组仅有的一个元素返回。

范例

Example 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
)

stripos

(PHP 5, PHP 7)

查找字符串首次出现的位置(不区分大小写)

说明

stripos ( string $haystack , string $needle [, int $offset = 0 ] ) : int

返回在字符串 haystackneedle 首次出现的数字位置。

strpos() 不同,stripos() 不区分大小写。

参数

haystack

在该字符串中查找。

needle

注意 needle 可以是一个单字符或者多字符的字符串。

如果 needle 不是一个字符串,那么它将被转换为整型并被视为字符顺序值。

offset 可选的 offset 参数,从字符此数量的开始位置进行搜索。 如果是负数,就从字符末尾此数量的字符数开始统计。

返回值 ¶ 返回 needle 存在于 haystack 字符串开始的位置(独立于偏移量)。同时注意字符串位置起始于 0,而不是 1。

如果未发现 needle 将返回 FALSE。

strlen

(PHP 4, PHP 5, PHP 7)

获取字符串长度

说明

strlen ( string $string ) : int

返回给定的字符串 string 的长度。

参数

string

需要计算长度的字符串。

返回值

成功则返回字符串 string 的长度;如果 string 为空,则返回 0。

范例

Example 1 strlen() 范例

<?php
$str = 'abcdef';
echo strlen($str); // 6

$str = ' ab cd ';
echo strlen($str); // 7
?>

strpos

(PHP 4, PHP 5, PHP 7)

查找字符串首次出现的位置

说明

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

返回 needlehaystack 中首次出现的数字位置。

参数

haystack

在该字符串中进行查找。

needle

查找的字符串

offset

如果提供了此参数,搜索会从字符串该字符数的起始位置开始统计。 如果是负数,搜索会从字符串结尾指定字符数开始。

返回值

返回 needle 存在于 haystack 字符串起始的位置(独立于 offset)。同时注意字符串位置是从 0 开始,而不是从 1 开始的。

如果没找到 needle,将返回 FALSE

范例

Example 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";
}
?>

Example 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'";
}
?>

Example 3 使用位置偏移量

<?php
// 忽视位置偏移量之前的字符进行查找
$newstring = 'abcdef abcdef';
$pos = strpos($newstring, 'a', 1); // $pos = 7, 不是 0
?>

strtolower

(PHP 4, PHP 5, PHP 7)

将字符串转化为小写

说明

strtolower ( string $string ) : string

string 中所有的字母字符转换为小写并返回。

参数

string

输入字符串。

返回值

返回转换后的小写字符串。

范例

Example 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
?>

strtoupper

(PHP 4, PHP 5, PHP 7)

将字符串转化为大写

说明

strtoupper ( string $string ) : string

string 中所有的字母字符转换为大写并返回。

参数

string

输入字符串。

返回值

返回转换后的大写字符串。

范例

Example 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
?>

trim

(PHP 4, PHP 5, PHP 7)

去除字符串首尾处的空白字符(或者其他字符)

说明

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

此函数返回字符串 str 去除首尾空白字符后的结果。如果不指定第二个参数,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 参数指定。一般要列出所有希望过滤的字符,也可以使用 “..” 列出一个字符范围。

返回值

过滤后的字符串。

范例

Example 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"

Example 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"
}

ucfirst

(PHP 4, PHP 5, PHP 7)

将字符串的首字母转换为大写

说明

ucfirst ( string $str ) : string

str 的首字符(如果首字符是字母)转换为大写字母,并返回这个字符串。

参数

str

输入字符串。

返回值

返回结果字符串。

范例

Example 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!
?>

ucwords

(PHP 4, PHP 5, PHP 7)

将字符串中每个单词的首字母转换为大写

说明

ucwords ( string $str [, string $delimiters = " \t\r\n\f\v" ] ) : string

str 中每个单词的首字符(如果首字符是字母)转换为大写字母,并返回这个字符串。

这里单词的定义是紧跟在 delimiters 参数(默认:空格符、制表符、换行符、回车符、水平线以及竖线)之后的子字符串。

参数

str

输入字符串。

delimiters

可选的 delimiters,包含了单词分割字符。

返回值

返回转换后的字符串。

范例

Example 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!
?>
Example #2 ucwords() 自定义 delimiters 的例子

<?php
$foo = 'hello|world!';
$bar = ucwords($foo);             // Hello|world!

$baz = ucwords($foo, "|");        // Hello|World!
?>