您的位置:首页 > 编程语言 > PHP开发

字符串函数--php基础最详细教程

2016-08-30 21:55 495 查看

字符串常用函数 原创

<?php

header('content-type:text/html;charset=utf-8');

date_default_timezone_set('PRC');

//字符串处理函数 

//去除空格或其他字符

//1.trim ltrim  rtrim 去除字符串首尾处/左边/右边的空白字符(或者其他字符)

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

//此函数返回字符串 str 去除首尾空白字符后的结果。如果不指定第二个参数, trim() 将去除这些字符:

//可选参数,过滤字符也可由 charlist 参数指定。一般要列出所有希望过滤的字符,也可以使用 ".." 列出一个字符范围。

$str = " abcdefhigk \n";

$str1 = trim($str);

echo $str1;

$str2 = trim($str," \n e..k");

echo '<br>';

echo $str2; //abcd 可以指定多个类型的值,可以用..表示

echo '<br>';

//ltrim he rtrim 同理。 chop()是 rtrim()别名

//2.目录和文件名函数 basename() dirname() pathinfo()

$file = 'c:/ays/bbs/dds/index.php';

echo dirname($file);

echo '<br>';

echo basename($file);

echo '<br>';

var_dump(pathinfo($file));

echo '<hr>';

//字符串生成和转化函数

//1.string str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] )

//该函数返回 input 被从左端、右端或者同时两端被填充到制定长度后的结果。如果可选的 pad_string 参数没有被指定,

//input 将被空格字符填充,否则它将被 pad_string 填充到指定长度。 

//可选的 pad_type 参数的可能值为 STR_PAD_RIGHT,STR_PAD_LEFT 或 STR_PAD_BOTH。如果没有指定 pad_type,则假定它是 STR_PAD_RIGHT。 

$str = 'abc';

$nstr = str_pad($str,10,'fff'); //默认填充在右边STR_PAD_RIGHT

echo $nstr;

echo '<br>';

$nstr = str_pad($str,9,'fff',STR_PAD_BOTH);

echo $nstr;

echo '<br>';

$nstr = str_pad($str,9,'fff',STR_PAD_LEFT);

echo $nstr;

echo '<hr>';

//2.string str_repeat ( string $input , int $multiplier )

//返回 input 重复 multiplier 次后的字符串。

$str = '中国加油! ';

echo str_repeat($str,10);

echo '<hr>';

//3.array str_split ( string $string [, int $split_length = 1 ] )

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

//如果 split_length 小于 1,返回 FALSE。如果 split_length 参数超过了 string 超过了字符串 string 的长度,

//整个字符串将作为数组仅有的一个元素返回

$str = 'my name is vilin';

var_dump(str_split($str)); //不指定长度,默认为一个字符长度。

var_dump(str_split($str,4)); //空格也会被看做一个字符。

echo '<hr>';

//4.string strrev ( string $string ) 返回 string 反转后的字符串。

$str = 'UOY EVOL I';

echo strrev($str);

echo '<hr>';

//5.string wordwrap ( string $str [, int $width = 75 [, string $break = "\n" [, bool $cut = false ]]] )

//使用字符串断点将字符串打断为指定数量的字串。 返回打断后的字符串。

//break 使用可选的 break 参数打断字符串。

//如果 cut 设置为 TRUE,字符串总是在指定的宽度或者之前位置被打断。因此,如果有的单词宽度超过了给定的宽度,它将被分隔开来。

$arr = "my name is pan xiao liang wo de jia zai dong beijjiiiiiiiiiii";

echo wordwrap($arr,5,"\n",true); //把超过5个字符的单子强制打断 查看源代码可看效果

echo '<br>';

//6.string str_shuffle ( string $str ) 函数打乱一个字符串,使用任何一种可能的排序方案。 

$str = 'ABCDEFGHIGKLMN';

echo str_shuffle($str);

echo '<br>';

//7.void parse_str ( string $str [, array &$arr ] )

//如果 str 是 URL 传递入的查询字符串(query string),则将它解析为变量并设置到当前作用域。

//如果设置了第二个变量 arr,变量将会以数组元素的形式存入到这个数组,作为替代。

$str = "first=value&arr[]=foo+bar&arr[]=baz";

parse_str($str);

echo $first;  // value

echo $arr[0]; // foo bar

echo $arr[1]; // baz

parse_str($str, $output); //把$str中的变量存入$output数组中

echo $output['first'];  // value

echo $output['arr'][0]; // foo bar

echo $output['arr'][1]; // baz

echo '<hr>';

//8.string number_format ( float $number [, int $decimals = 0 ] )  以千位分隔符方式格式化一个数字

//string number_format ( float $number , int $decimals = 0 , string $dec_point = '.' , string $thousands_sep = ',' )

//第二种用法必须同时指定第三个 第四个参数。

//decimals 要保留的小数位数 

//本函数可以接受1个、2个或者4个参数(注意:不能是3个): 

$str = 3689.6365;

echo number_format($str);//不指定第二参数将不保留小数点。会自动四舍五入。

echo '<br>';

echo number_format($str,2); //保留两位会进行四舍五入

echo '<br>';

echo number_format($str,2,'#','@'); #替换默认小数点 @ 替换,

echo '<hr>';

//9. strtoupper() strtolower() ucfirst() ucwords()  字母大小写转换

// string strtoupper ( string $string ) 将 string 中所有的字母字符转换为大写并返回。 

//string strtolower ( string $str ) 将 string 中所有的字母字符转换为小写并返回。 

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

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

$foo = 'hello world!';

$foo = ucwords($foo);             // Hello World!

$bar = 'HELLO WORLD!';

$bar = ucwords($bar);             // HELLO WORLD!

$bar = ucwords(strtolower($bar)); // Hello World!

echo '<hr>';

//html标签相关函数

//1. nl2br() htmlentities() htmlspecialchars() strip_tags()

//string nl2br ( string $string [, bool $is_xhtml = true ] ) 在字符串 string 所有新行之前插入 '<br />' 或 '<br>',并返回。 

//string htmlentities ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = 'UTF-8' 

//[, bool $double_encode = true ]]] ) 把html标签转换成字符实体。

//htmlspecialchars() htmlentities()

//string strip_tags ( string $str [, string $allowable_tags ] ) 从字符串中去除 HTML 和 PHP 标记

//该函数尝试返回给定的字符串 str 去除空字符、HTML 和 PHP 标记后的结果。它使用与函数 fgetss() 一样的机制去除标记。 

//allowable_tags  使用可选的第二个参数指定不被去除的字符列表。

$string = "This\r\nis\n\ra\nstring\r";

echo nl2br($string);

//输出为一下内容

//This<br />

//is<br />

//a<br />

//string<br />

$str = "A 'quote' is <b>bold</b>";

// Outputs: A 'quote' is <b>bold</b>

echo htmlentities($str);

echo '<hr>';

$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';

echo strip_tags($text);

echo '<br>';

// 允许 <p> 和 <a>

echo strip_tags($text, '<p><a>'); //第二参数指定允许的内容。

echo '<hr>';

//2.string addcslashes ( string $str , string $charlist ) 返回字符串,该字符串在属于参数 charlist 列表中的字符前都加上了反斜线。

$str = "mynnamenisnvilin";

$str2 = addcslashes($str,"n");

echo $str2;

echo '<br>';

//3.string stripcslashes ( string $str ) 返回反转义后的字符串。可识别类似 C 语言的 \n,\r,... 八进制以及十六进制的描述。 

echo stripcslashes($str2);

echo '<br>';

//4.string addslashes ( string $str )

//返回字符串,该字符串为了数据库查询语句等的需要在某些字符前加上了反斜线。

//这些字符是单引号(')、双引号(")、反斜线(\)与 NUL(NULL 字符)。

//PHP 5.4 之前 PHP 指令 magic_quotes_gpc 默认是 on,

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

// 输出: Is your name O\'reilly?

echo addslashes($str);

echo '<br>';

//5.string stripslashes ( string $str )

//反引用一个引用字符串。如果 magic_quotes_sybase 项开启,反斜线将被去除,但是两个反斜线将会被替换成一个。

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

echo '<br>';

// 输出: Is your name O'reilly?

echo stripslashes($str);

echo '<br>';

//string quotemeta ( string $str )

$str = "Hello world. (can you hear me?)";

 echo quotemeta($str);

echo '<br>';

//int ord ( string $string )返回字符串 string 第一个字符的 ASCII 码值。

// string chr ( int $ascii ) 返回相对应于 ascii 所指定的单个字符。

//字符串比较函数

//strcmp() strcasecmp() strncmp() strncasecmp() strnatcmp() strnatcasecmp()

//int strcmp ( string $str1 , string $str2 ) 二进制安全字符串比较 区分大小写。

//int strcasecmp ( string $str1 , string $str2 )二进制安全字符串比较 不区分大小写。

////返回值 如果 str1 小于 str2 返回 < 0; 如果 str1 大于 str2 返回 > 0;如果两者相等,返回 0。

//int strncmp ( string $str1 , string $str2 , int $len ) 注意该比较区分大小写。

//int strncasecmp ( string $str1 , string $str2 , int $len ) 不区分大小写

//该函数与 strcmp() 类似,不同之处在于你可以指定两个字符串比较时使用的长度(即最大比较长度)。 

//返回值 如果 str1 小于 str2 返回 < 0; 如果 str1 大于 str2 返回 > 0;如果两者相等,返回 0。 

//int strnatcmp ( string $str1 , string $str2 )  使用自然排序算法比较字符串区分大小写

//int strnatcasecmp ( string $str1 , string $str2 ) 使用自然排序算法比较字符串不区分大小写

//与其他字符串比较函数类似,如果 str1 小于 str2 返回 < 0; 如果 str1 大于 str2 返回 > 0;如果两者相等,返回 0。 

//字符串切割与拼接

//1.string chunk_split ( string $body [, int $chunklen = 76 [, string $end = "\r\n" ]] )

//使用此函数将字符串分割成小块非常有用。例如将 base64_encode() 的输出转换成符合 RFC 2045 语义的字符串。

//它会在每 chunklen 个字符后边插入 end。 

$str = "Yar?m kilo ?ay, yar?m kilo ?eker";

$str = "Yar?m kilo ?ay, yar?m kilo ?eker";

 echo chunk_split($str, 4)."\n";

echo '<br>';

//string strtok ( string $str , string $token )

//string strtok ( string $token )

 $string = "This is\tan example\nstring";

/* 使用制表符和换行符作为分界符 */

$tok = strtok($string, " \n\t");

echo '<br>';

while ($tok !== false) {

    echo "Word=$tok<br />";

    $tok = strtok(" \n\t");

}

//2.array explode ( string $delimiter , string $string [, int $limit ] )

//此函数返回由字符串组成的数组,每个元素都是 string 的一个子串,它们被字符串 delimiter 作为边界点分割出来。

//如果设置了 limit 参数并且是正数,则返回的数组包含最多 limit 个元素,而最后那个元素将包含 string 的剩余部分。 

//如果 limit 参数是负数,则返回除了最后的 -limit 个元素外的所有元素。 

//如果 limit 是 0,则会被当做 1。 

$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";

$pieces = explode(" ", $pizza);  //用空格截取字符串。

var_dump($pieces);

//3.string implode ( string $glue , array $pieces ) 用 glue 将一维数组的值连接为一个字符串。

//string implode ( array $pieces ) 因为历史原因 implode()的参数顺序可以是随意的, explode()也一样

$array = array('lastname', 'email', 'phone');  //join() — 别名 implode()

$comma_separated = implode(",", $array);

echo $comma_separated; // lastname,email,phone

echo '<br>';

//4.string substr ( string $string , int $start [, int $length ] )

//返回字符串 string 由 start 和 length 参数指定的子字符串

$rest = substr("abcdef", 0, -1);  // 返回 "abcde"

$rest = substr("abcdef", 2, -1);  // 返回 "cde"

$rest = substr("abcdef", 4, -4);  // 返回 ""

$rest = substr("abcdef", -3, -1); // 返回 "de"

echo '<br>';

//字符串查找替换

//1.mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

// mixed str_ireplace ()  不区分大小写。

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

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

$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);

$str = str_replace("ll", "", "good golly miss molly!", $count);

echo $count;

echo '<hr>';

//2.int substr_count ( string $haystack , string $needle [, int $offset = 0 [, int $length ]] )\

//substr_count() 返回子字符串needle 在字符串 haystack 中出现的次数。注意 needle 区分大小写。 

$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 i',所以输出 0

echo substr_count($text, 'is', 3, 3);

// 因为 5+10 > 14,所以生成警告

echo substr_count($text, 'is', 5, 10);

// 输出 1,因为该函数不计算重叠字符串

$text2 = 'gcdgcdgcd';

echo substr_count($text2, 'gcdgcd');

echo '<hr>';

//3.mixed substr_replace ( mixed $string , mixed $replacement , mixed $start [, mixed $length ] )

//在字符串 string 的副本中将由 start 和可选的 length 参数限定的子字符串使用 replacement 进行替换。 

$var = 'ABCDEFGH:/MNRPQR/';

echo "Original: $var<hr />\n";

/* 这两个例子使用 "bob" 替换整个 $var。*/

echo substr_replace($var, 'bob', 0) . "<br />\n";

echo substr_replace($var, 'bob', 0, strlen($var)) . "<br />\n";

/* 将 "bob" 插入到 $var 的开头处。*/

echo substr_replace($var, 'bob', 0, 0) . "<br />\n";

/* 下面两个例子使用 "bob" 替换 $var 中的 "MNRPQR"。*/

echo substr_replace($var, 'bob', 10, -1) . "<br />\n";

echo substr_replace($var, 'bob', -7, -1) . "<br />\n";

/* 从 $var 中删除 "MNRPQR"。*/

echo substr_replace($var, '', 10, -1) . "<br />\n";

echo '<hr>';

//4.计算两个字符串的相似度

//int similar_text ( string $first , string $second [, float &$percent ] )

$str = 'abcde woc';

$str1 = 'abc wig';

echo similar_text($str, $str1,$nums);  //输出相似的字符数量 。

echo '<br>';

echo $nums; //传入一个变量 来计算相似度 float值

echo '<br>';

//5.string strrchr ( string $haystack , mixed $needle )

//该函数返回 haystack 字符串中的一部分,这部分以 needle 的最后出现位置开始,直到 haystack 末尾。

//如果 needle 包含了不止一个字符,那么仅使用第一个字符。该行为不同于 strstr()。 

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

// 获取 $PATH 中不含磁盘符号的目录

//$dir = substr(strrchr($PATH, ":"), 1);

// 获取最后一行内容

$text = "Line 1\nLine 2\nLine 3";

$chr = strrchr($text, 10);

$last = substr($chr, 1 );//不计算空格从1开始第10个是 2 

echo $chr; //Line 3 

echo '<hr>';

//6.string strstr ( string $haystack , mixed $needle [, bool $before_needle = false ] )

//返回 haystack 字符串从 needle 第一次出现的位置开始到 haystack 结尾的字符串。 

//before_needle 若为 TRUE, strstr() 将返回 needle 在 haystack 中的位置之前的部分。 

//用法同strrchr 区别为这个是从首次出现到最后,还有第三参数。 

//不区分大小写 使用stristr()

$email  = 'name@example.com';

$domain = strstr($email, '@');

echo $domain; // 打印 @example.com

$user = strstr($email, '@', true); // 从 PHP 5.3.0 起

echo $user; // 打印 name

//7.string strtr ( string $str , string $from , string $to )

//string strtr ( string $str , array $replace_pairs )

//该函数返回 str 的一个副本,并将在 from 中指定的字符转换为 to 中相应的字符。 

//比如, $from[$n]中每次的出现都会被替换为 $to[$n],其中 $n 是两个参数都有效的位移(offset)。 

//如果 from 与 to 长度不相等,那么多余的字符部分将被忽略。 str 的长度将会和返回的值一样。 

$trans = array("hello" => "hi", "hi" => "hello");

echo strtr("hi all, I said hello", $trans);

echo '<hr>';

//例程会输出:

//hello all, I said hi

//8.mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

//返回 needle 在 haystack 中首次出现的数字位置。 

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

//offset如果提供了此参数,搜索会从字符串该字符数的起始位置开始统计。

//和 strrpos()、 strripos()不一样,这个偏移量不能是负数。

//stripos 不区分大小写 

$mystring = 'abc';

$findme   = 'a';

$pos = strpos($mystring, $findme);

echo $pos; //0 

echo '<br>'; 

//9.int strrpos ( string $haystack , string $needle [, int $offset = 0 ] )

//返回字符串 haystack 中 needle 最后一次出现的数字位置。注意 PHP4 中,

//needle 只能为单个字符。如果 needle 被指定为一个字符串,那么将仅使用第一个字符。 

//和strpos 使用方法一样,区别是在最后一次出现的数字位置。 

//strripos 不区分大小写

$foo = "0123456789a123456789b123456789c";

var_dump(strrpos($foo, '7', -5));  // 从尾部第 5 个位置开始查找

                                   // 结果: int(17)

var_dump(strrpos($foo, '7', 20));  // 从第 20 个位置开始查找

                                   // 结果: int(27)

var_dump(strrpos($foo, '7', 28));  // 结果: bool(false)

echo '<hr>';

//9.int strspn ( string $subject , string $mask [, int $start [, int $length ]] )

//返回 subject 中全部字符仅存在于 mask 中的第一组连续字符(子字符串)的长度。 

//如果省略了 start 和 length 参数,则检查整个 subject 字符串;如果指定了这两个参数,

//则效果等同于调用 strspn(substr($subject, $start, $length), $mask)

//int strcspn ( string $str1 , string $str2 [, int $start [, int $length ]] )

//返回 str1 中,所有字符都不存在于 str2 范围的起始子字符串的长度。

$var = strspn("42 is the answer to the 128th question.", "1234567890");

//$var 将被指派为 2,因为 '42' 是 subject 中第一段全部字符都存在于 '1234567890' 的连续字符。

echo strspn("foo", "o", 1, 2); // 打印: 2

//以上例程会输出:

//int(0)

//int(2)

//int(1)

echo '<hr>';

//字符串统计函数

//1.mixed str_word_count ( string $string [, int $format = 0 [, string $charlist ]] )

//统计 string 中单词的数量。如果可选的参数 format 没有被指定,那么返回值是一个代表

//单词数量的整型数。如果指定了 format 参数,返回值将是一个数组,数组的内容则取决于 format 参数。

//format 的可能值和相应的输出结果如下所列。 

//对于这个函数的目的来说,单词的定义是一个与区域设置相关的字符串。这个字符串可以包含字母字符,

//也可以包含 "'" 和 "-" 字符(但不能以这两个字符开始)。 

//format

//指定函数的返回值。当前支持的值如下: 

//• 0 - 返回单词数量  

//• 1 - 返回一个包含 string 中全部单词的数组  

//• 2 - 返回关联数组。数组的键是单词在 string 中出现的数值位置,数组的值是这个单词 

//charlist 附加的字符串列表,其中的字符将被视为单词的一部分。

//返回一个数组或整型数,这取决于 format 参数的选择。 

$str = "Hello fri3nd, you're

       looking          good today!";

print_r(str_word_count($str, 1));

print_r(str_word_count($str, 2));

print_r(str_word_count($str, 1, 'àá??3'));

echo str_word_count($str);

/**以上例程会输出:

Array

(

    [0] => Hello

    [1] => fri

    [2] => nd

    [3] => you're

    [4] => looking

    [5] => good

    [6] => today

)

Array

(

    [0] => Hello

    [6] => fri

    [10] => nd

    [14] => you're

    [29] => looking

    [46] => good

    [51] => today

)

Array

(

    [0] => Hello

    [1] => fri3nd

    [2] => you're

    [3] => looking

    [4] => good

    [5] => today

)

7

*/

echo '<hr>';

//2.int strlen ( string $string )

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

$str = 'abcdef';

echo strlen($str); // 6

$str = ' ab cd ';

echo strlen($str); // 7

echo '<hr>';

//3.mixed count_chars ( string $string [, int $mode = 0 ] )

//统计 string 中每个字节值(0..255)出现的次数,使用多种模式返回结果。

//返回值

//根据不同的 mode, count_chars() 返回下列不同的结果: 

//• 0 - 以所有的每个字节值作为键名,出现次数作为值的数组。  

//• 1 - 与 0 相同,但只列出出现次数大于零的字节值。  

//• 2 - 与 0 相同,但只列出出现次数等于零的字节值。  

//• 3 - 返回由所有使用了的字节值组成的字符串。  

//• 4 - 返回由所有未使用的字节值组成的字符串。 

$data = "Two Ts and one F.";

foreach (count_chars($data, 1) as $i => $val) {

   echo "There were $val instance(s) of \"" , chr($i) , "\" in the string.\n";

}

 

/*以上例程会输出:

There were 4 instance(s) of " " in the string.

There were 1 instance(s) of "." in the string.

There were 1 instance(s) of "F" in the string.

There were 2 instance(s) of "T" in the string.

There were 1 instance(s) of "a" in the string.

There were 1 instance(s) of "d" in the string.

There were 1 instance(s) of "e" in the string.

There were 2 instance(s) of "n" in the string.

There were 2 instance(s) of "o" in the string.

There were 1 instance(s) of "s" in the string.

There were 1 instance(s) of "w" in the string.

*/

//字符串编码

//1.string md5 ( string $str [, bool $raw_output = false ] )

//使用 » RSA 数据安全公司的 MD5 报文算法计算 str 的 MD5 散列值。 

$str = 'apple';

if (md5($str) === '1f3870be274f6c49b3e31a0c6728957f') {

    echo "Would you like a green or red apple?";

}

分支主题 2

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息