字符串函数学习一
1.wordwrap 打断字符串为指定数量的字串
$text="shang ban jiu shi wei le huo zhe ";
$new_text=wordwrap($text,20,"<br/>\n");
print_r($new_text);
2.vsprintf 返回格式化字符串
print_r(vsprintf("%04d-%02d-%02d",explode('-','2020-10-1')));
3.vprintf 输出格式化字符串
print_r(vprintf("%04d-%02d-%02d",explode('-','2020-10-1')));
4. ucwords将字符串中每个单词的首字母转换为大写
$text1='come on';
echo(ucwords($text1)).("<br/>\n");
$text2='COME ON';
echo(strtolower($text2)).("<br/>\n");
echo(ucwords(strtolower($text2))).("<br/>\n");
$text3='come|on';
echo(ucwords($text3)).("<br/>\n");
echo(ucwords($text3,'|')).("<br/>\n");
5.ucfirst 将字符串的首字母转换为大写
$text1='come on';
echo(ucfirst($text1)).("<br/>\n");
$text2='COME ON';
echo(strtolower($text2)).("<br/>\n");
echo(ucfirst(strtolower($text2))).("<br/>\n");
$text3='come|on';
echo(ucfirst($text3)).("<br/>\n");
6.trim 去除字符串收尾处的空白字符(或其他字符)
$text1=' come on ';
echo(trim($text1)).("<br/>\n");
$text2='CCOME ONC';
echo(trim($text2,'C')).("<br/>\n");
$text3='come on|';
echo(trim($text3,'|')).("<br/>\n");
7.substr 返回字符串的子串
$rest = substr("abcdef", 1); //返回"bcdef"
$rest = substr("abcdef", 1,4); //返回"bcde"
$rest = substr("abcdef", 0, -1); // 返回 "abcde"
$rest = substr("abcdef", 2, -1); // 返回 "cde"
$rest = substr("abcdef", 4, -4); // 返回 ""
$rest = substr("abcdef", -3, -1); // 返回 "de"
8.substr_replace替换字符串的子串
echo substr_replace("Hello","world",0);
echo substr_replace("Hello world","Shanghai",6);
echo substr_replace("Hello world","Shanghai",-5);
echo substr_replace("world","Hello ",0,0);
$replace = array("1: AAA","2: AAA","3: AAA");
echo implode("<br>",substr_replace($replace,'BBB',3,3));
9.substr_count()计算字串出现的次数
$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');
10.substr_compare 二进制安全比较字符串(从偏移位置比较指定长度)
echo substr_compare("abcde", "bc", 1, 2); // 0
echo substr_compare("abcde", "de", -2, 2); // 0
echo substr_compare("abcde", "bcg", 1, 2); // 0
echo substr_compare("abcde", "BC", 1, 2, true); // 0
echo substr_compare("abcde", "bc", 1, 3); // 1
echo substr_compare("abcde", "cd", 1, 2); // -1
echo substr_compare("abcde", "abc", 5, 1); // warning
本作品采用《CC 协议》,转载必须注明作者和本文链接