本文只要介绍了常用的字符串操作,其中包括字符串去首尾空格,获得字符串长度,连接、分隔字符串,转义字符串,截取字符串,字符串查找和替换
从字符串定义到高层字符串处理技巧。
字符串是指游零个或多个字符构成的集合。
单引号:所见即所得 双引号:经过PHP语法分析器解析过,变量被替换为值
<?php $s1 = "Jesus is the life"; $s2 = 'Jesus is the life'; echo '$s1 '.$s1.'<br>'; # $s1 Jesus is the life echo '$s2 '.$s2.'<br>'; # $s2 Jesus is the life $attr = 'love'; $str1 = "Jesus is the $attr"; $str2 = 'Jesus is the $attr'; echo '$str1 '.$str1.'<br>'; # $str1 Jesus is the love echo '$str2 '.$str2.'<br>'; # $str2 Jesus is the $attr ?>在字符串中,使用反斜杠(\)转义 echo "I\'m Christian";
addslashes():为字符串str加入反斜杠\ string addslashed(string str)
addcslashes():在指定字符安charlist前加上”\”; string addcslashed(string str, string charlist) charlist指定在哪些字符前加上”\”,\n,\r等以C语言转换,其他非字符数字且ASCII码低于32或高于126的字符安转换为八进制表示。需要明确在开始和结束范围内的字符串
stripslashes():将addslashes()转义后的字符串str返回原样 string stripslashes(string str)
stripcslashes():将addcslashes()转义后的字符串str返回原样 string stripcslashes(string str)
<?php $str = "不从恶人的计谋,不站罪人的道路"; echo $str.'<br>'; # 不从恶人的计谋,不站罪人的道路 $slashesed = addcslashes($str, "不站罪人的道路"); echo $slashesed.'<br>'; #\344\270\215\344���\201�\344\272\272\347\... $restore = stripcslashes($slashesed); echo $restore.'<br>'; # 不从恶人的计谋,不站罪人的道路 ?>手动转义适用于简单的字符串 自动转义适用于数据量较大的字符串
int strlen(string str) 汉字占两个字符,数字、英文、小数点、下划线和空格占一个字符
string substr(string str, int start [, int length]) start的指定位置从0开始计算 截取中文字符串的个数是奇数的话会出现乱码
相等返回0; str1 > str2, 返回值 > 0; str1 < str2, 返回值 < 0;
strcmp()区分字母大小写 int strcmp(string str1, string str2)
strcasecmp()不区分大小写,其他和strcmp一致
strncmp()比较字符串的前n个字符,区分大小写 int strncmp(string str1, string str2, int len)
int substr_count(string haystack, string needle) 一般用于搜索引擎
str_ireplace()使用新的子串替换原始字符串中被指定要替换的字符串 mixed str_ireplace(mixed search, mixed replace, mixed subject[, int &count])
将所有在参数subject中出现的参数search以参数replace取代 不区分大小写
str_replace() 区分大小写,其他和str_ireplace()一致substr_replace()对指定字符串中的部分字符串中进行替换 string substr_replace(string str, string repl, int start[, int length]) 如果start是负数,而参数length>=start,那么length== 0explode()按照指定规则对字符串分割,返回数组 array explode(string sqparator, string str[, int limit])
$str="Jesus is the way@Jesus is the truth@Jesus is the life"; $str_arr=explode("@",$str); print_r($str_arr); # Array ( [0] => Jesus is the way [1] => Jesus is the truth [2] => Jesus is the life )implode()可以将数组的内容组合成新字符串 string implode(string glue, array pieces) glue指定分隔符 pieces指定要被合并的数组
$str="Jesus is the way@Jesus is the truth@Jesus is the life"; echo $str.'<br>'; $str_arr=explode("@",$str); print_r($str_arr); echo '<br>'; $array=implode("@",$str_arr); echo $array; # Jesus is the way@Jesus is the truth@Jesus is the life