php中字符串常见的操作

字符串

长度

$str = 'helloworld';
strlen($str);// int(8)
mb_strlen('哈喽');// int(2) 在这是utf8编码环境下

格式

$str = '%d %b %.2f %.2e %s %%';
sprintf($str, 10, 11, 1.2, 1.2e2, 'hw');
// 10 1011 1.20 1.20e+2 hw %

大小写

$str = 'helloworld is helloworld!';
ucfirst($str);// Helloworld is helloworld! // 字符串首字母转大写
ucwords($str);// Helloworld Hs Helloworld! // 每个单词首字母 转大写
strtoupper($str);// HELLOWORLD IS HELLOWORLD! // 所有字母 转大写
strtolower($str);// helloworld is helloworld! // 所有字母 转小写

substr

$str = 'helloworld';
substr($str, 0, 2);// 'ya'

strstr, stristrstrrchr

$str = 'helloworld';
strstr($str, 'n');// 区分大小写正向从第一个n处开始返回字符串 'njing'
stristr($str, 'n');// 不区分大小写正向从第一个n处开始返回字符串 'Ngnjing'
strrchr($str, 'n');// 区分大小写正向从第一个n处开始返回字符串 'ng'

str_replacestr_ireplace

$a =  date('Y-m-d-H-i-s', time());
$a;// 2020-01-01-09-33-34
str_replace('-', '', $a);// 20200101093334
//  str_ireplace 不区分大小写 
// str_replace 和 str_replace 找不到字符串中的目标就会原样输出字符串 

strpos ,strrpos ,stripos,strripos

$str = 'helloworld';
strpos( $str, 'o' );// int(4)
strrpos( $str, 'o' );// int(6)
stripos( $str, 'O' );// int(4)
strripos( $str, 'O' );// int(6)

删除空白字符

```php
$str = ' helloworld ';
ltrim($str);// 'helloworld ' // 删除左方
rtrim($str);// ' helloworld' // 删除右方
trim($str);// 'helloworld' // 删除左右两方

猜你喜欢

转载自www.cnblogs.com/zxcv123/p/12129468.html