首页 > 代码库 > php之常用字符串方法

php之常用字符串方法

1.trim:去除字符串首尾出的空白字符(或其他字符)
eg:
$text = "            there are a few words.       ";
print_r(trim($text));
2.ltrim:去除左边的空白字符.

3.rtrim:去除右边的空白字符.
4.str_pad():按需求对字符串进行填充.第一个参数是要填充的字符串,第二个是填充长度,第三个参数是填充的符号,
第四个参数是填充的方向(
STR_PAD_LEFT:字符串左添补.
STR_PAD_RIGHT:字符串右添补.
STR_PAD_BOTH:字符串两端添补

eg:
$input = "Alice.";

echo str_pad($input,10,"-="); //Alice.-=-=
echo str_pad($input,15,"**",STR_PAD_BOTH);  //****Alice.*****
5.strtolower():将字符串str全部变小写字符串.
6.strtoupper():本函数将字符串str全部变大写字符串.

7.ucfirst():字符串第一个字符改大写.
8.ucwords():字符串每个字第一个字母改大写.
9.nl2br():将字符串"\n"转成HTML换行符"<br/>";第二个参数表示是否使用XHTML兼容换行符
eg:
echo nl2br("welcome\r\nThis is my HTML document",false);//welcome
This is my HTML document
10.htmlspecialchars():把指定特殊符号转成实体,如&lt;&gt;等等
eg:
echo htmlspecialchars("<a href=http://www.mamicode.com/‘#‘>Test");//<a href=http://www.mamicode.com/‘#‘>Test
11.strip_tags():从字符串中去除HTML和PHP标记.
eg:
$text1 = "<p>Test paragraph.</p><!-- Comment --><a href=http://www.mamicode.com/‘#‘>Other text";
echo $text1;//Test paragraph.
               Other text


12.strrev():将字符串前后颠倒.反转字符串.
$text2 = "hello world";
echo strrev($text2);//dlrow olleh


13.strlen():获取字符串长度.

14.number_format():以千位分隔符方式格式化一个数字
eg:
$number = 1234.56;
echo number_format($number);//1,235
echo  number_format($number,2);//1,234.56
echo  number_format($number,2,",","");//1234,56
15.md5():加密函数
16.strcmp():二进制安全字符串比较
eg:
$var1 = "hello";
$var2 = "Hello";
if(strcmp($var1,$var2)!== 0){
echo "$var1 is not equal to $var2 in a case sensitive string comarison";
}
17.strncmp():二进制安全比较字符串开头的若干个字符;与strcmp相似,不同在于可以指定两个字符串比较时使用的长度.

eg:
$arr1 = $arr2 = array("img12.png","img10.png","img2.png","img1.png");

usort($arr1,"strcmp");//Array ( [0] => img1.png [1] => img10.png [2] => img12.png [3] => img2.png ) 
18.strcasecmp():二进制安全比较字符串(不区分大小写)
19.strnatcmp():使用自然排序算法比较字符串
eg:
$arr1 = $arr2 = array("img12.png","img10.png","img2.png","img1.png");

usort($arr2,"strnatcmp");//Array ( [0] => img1.png [1] => img2.png [2] => img10.png [3] => img12.png )
20.similar_text():计算两个字符串的相似度


php之常用字符串方法