PHP中常用的十个字符串函数
explode
【ikˈsplōd】
使用字符串做为另一个字符串的分隔符,返回包含分割结果的数组。
<?php
@see https://www.php.net/manual/zh/function.explode.php
// explode ( string $delimiter , string $string [, int $limit ] ) : array
print_r(explode(' ','a b c d'));
Array
(
[0] => a
[1] => b
[2] => c
[3] => d
)
implode
【imˈplōd】
将一个一维数组转为字符串。
<?php
@see https://www.php.net/manual/zh/function.implode.php
// implode ( string $glue , array $pieces ) : string
$array = ['a','b','c','d'];
print_r(implode('', $array));
// abcd
trim
【trɪm】
去除字符串首尾的某些字符。
该函数接收两个参数,第一个为要处理的字符串,第二个为要去除的首尾字符。
第二个参数默认为" \t\n\r\0\x0B",可自行指定。
<?php
@see https://www.php.net/manual/zh/function.trim.php
// trim ( string $str [, string $character_mask = " \t\n\r\0\x0B" ] ) : string
$string = ' content
';
echo $string;
echo trim($string);
直接输出内容为" content
"
使用trim函数后输出内容为"content"
// 自定义去除字符
$string = '12content12';
echo trim($string, '12');
// content
str_replace
【str_riˈplās】
在一个字符串或数组中搜索并替换,返回替换后的字符串或数组。
<?php
@see https://www.php.net/manual/zh/function.str-replace.php
// str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] ) : mixed
$string = 'content';
echo str_replace('t', 'T', $string);
// conTenT
// 数组替换
$array = ['content1','content2'];
print_r(str_replace('t', 'T', $array));
Array
(
[0] => conTenT1
[1] => conTenT2
)
strlen
获取字符串长度
<?php
@see https://www.php.net/manual/zh/function.strlen.php
// strlen ( string $string ) : int
echo strlen('content');
// 7
strip_tags
从字符串中去除 HTML 和 PHP 标记。
第一个参数为要处理的字符串,第二个可选参数为不去除的标记白名单。
<?php
@see https://www.php.net/manual/zh/function.strip-tags.php
// strip_tags ( string $str [, string $allowable_tags ] ) : string
echo strip_tags('<span>content</div><script>', '<span>');
// <span>content
addslashes
使用反斜线转义单引号、双引号、反斜线与NULL。
<?php
@see https://www.php.net/manual/zh/function.addslashes.php
// addslashes ( string $str ) : string
$string = "content'";
echo addslashes($string);
// content\'
strrev
反转字符串
<?php
@see https://www.php.net/manual/zh/function.strrev.php
// strrev ( string $string ) : string
$string = "content";
echo strrev($string);
// tnetnoc
urlencode
URL需要遵守统一编码规范,服务端才能收到客户端想传递的正确数据。
除了大小写字母、数组和一些符号,其他例如空格、中文等等都会进行编码,会将ASCII码集之外的转换为%加上相应的16进制。
<?php
@see https://www.php.net/manual/zh/function.urlencode.php
// urlencode ( string $str ) : string
$string = "?wd=asdf 中文+-=";
echo urlencode($string);
// %3Fwd%3Dasdf+%E4%B8%AD%E6%96%87%2B-%3D
strpos
查找字符串首次出现的位置
<?php
@see https://www.php.net/manual/zh/function.strpos.php
// strpos ( string $haystack , mixed $needle [, int $offset = 0 ] ) : int
// 返回 needle 在 haystack 中首次出现的数字位置。
$haystack = 'abc';
$needle = 'a';
var_dump(strpos($haystack, $needle));
// int(0)
$haystack = 'abc';
$needle = 'b';
var_dump(strpos($haystack, $needle));
// int(1)
$haystack = 'abc';
$needle = 'd';
var_dump(strpos($haystack, $needle));
// bool(false)