php常用字符串总结

php常用字符串总结

代码块

strlen
功能是输出字符串的长度

<?php

$str = 'hello world';
$result = strlen($str);
echo $result;//输出字符串长度 11

$str2 = '你好 世界';
$result2 = mb_strlen($str2,'utf8');//中文
echo $result2;//输出字符串长度 5

?>

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

<?php

$str2 = ' 你好 世界 ';
$result2 = mb_strlen(trim($str2),'utf8');
echo $result2;//输出字符串长度 5

$str3 = ' 你好 世界 ';
$result3 = mb_strlen(ltrim($str3),'utf8');//去左空格
echo $result3;//输出字符串长度 6

$str4 = ' 你好 世界 ';
$result4 = mb_strlen(rtrim($str4),'utf8');//去右空格
echo $result4;//输出字符串长度 6

?>

substr
功能是返回字符串的子串

<?php
//string substr ( string $string , int $start [, int $length ] )
$str = 'hello world';
$result = substr($str,1);
echo $result;//输出ello world

$str2 = 'hello world';
$result2 = substr($str2,2,2);
echo $result2;//输出ll

?>

substr_count
功能是计算字串出现的次数

<?php
//int substr_count ( string $haystack , string $needle [, int $offset = 0 [, int $length ]] )
$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 is',因此输出 1
echo substr_count($text, 'is', 3,4);

?>

substr_replace
功能是替换字符串的子串

<?php
//mixed substr_replace ( mixed $string , mixed $replacement , mixed $start [, mixed $length ] )

$text = 'This is a test';
echo substr_replace($text, 'mm',0,0);//mmThis is a test
echo substr_replace($text, 'bbaa',1,2); // Tbbaas is a test
echo substr_replace($text, '',10,-2);//This is a st
?>

strtolower
strtoupper
ucfirst
lcfirst
功能是将字符串转化为大小写

<?php

$text = 'This is a test';
$text2 = 'this is a test';
echo strtolower($text);//全部转小写
echo strtoupper($text);//全部转大写
echo ucfirst($text);//将字符串的首字母转换为大写
echo lcfirst($text);//将字符串的首字母转换为小写
echo ucwords($text2);//将字符串中每个单词的首字母转换为大写

?>

echo
die
功能是输出字符串

<?php

$text = 'This is a test';
echo $text;//输出
die($text);//退出前输出
echo $text;//,没有执行

?>

nl2br

功能是 在字符串所有新行之前插入 HTML 换行标记

<?php

$text2 = $text2 = "this is\na <b>test</b>\n".' not action \n';

echo nl2br($text2);//单引号里未执行

?>

strip_tags

功能是 从字符串中去除 HTML 和 PHP 标记

<?php

$text2 = "this is\na <b>test</b>\n";

echo nl2br($text2);

?>

join

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

<?php

$text2 = array(1,6,2,3);

echo join($text2,'-');//用横线连接成字符串
echo implode($text2,'-');//用横线连接成字符串,与join一样
?>

md5

功能是 从字符串中去除 HTML 和 PHP 标记

<?php

$text2 = "this is\na <b>test</b>\n";

echo md5($text2);//md5算法加密

?>

strrev

功能是 反转字符串

<?php

$text2 = "this is a test";

echo strrev($text2);//输出tset a si siht

?>

strpos

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

<?php

$text2 = "this is a test";

echo strpos($text2,'is');//输出2
echo stripos($text2,'IS');//输出2
?>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值