006_string.php

<?php
$txt1 = "Hello";
$txt2 = "World";
echo $txt1 . " " . $txt2 . PHP_EOL; //拼接

echo strlen($txt1) . PHP_EOL; //字符串长度
$name = "Leyland";
echo strpos($name, "y") . PHP_EOL; //查找字符串位置
$result = strpos($name, "ya");
if ($result) {
    echo "Found" . PHP_EOL;
} else {
    echo "Not Found" . PHP_EOL;
}

echo substr("leyland", 2, 3) . PHP_EOL; //截取字符串

echo str_starts_with("leyland", "le") . PHP_EOL; //判断字符串是否以指定字符串开头
echo str_ends_with("leyland", "nd") . PHP_EOL; //判断字符串是否以指定字符串结尾

echo str_replace("ley", "Ley", "leyland") . PHP_EOL;
echo str_replace("ley", "Ley", "leylandleyland", $count) . PHP_EOL; //替换字符串,返回替换次数
echo $count . PHP_EOL;

echo strtolower("LEYLAND") . PHP_EOL; //转换为小写
echo strtoupper("leyland") . PHP_EOL; //转换为大写
echo ucfirst("leyland") . PHP_EOL; //首字母大写

echo trim("  leyland  ") . PHP_EOL; //去除首尾空格
echo ltrim("  leyland  ") . PHP_EOL; //去除左侧空格
echo rtrim("  leyland  ") . PHP_EOL; //去除右侧空格

echo md5("leyland") . PHP_EOL; //查看字符串的md5码
echo sha1("leyland") . PHP_EOL;  //查看字符串的sha1码
echo crypt("leyland", "salt") . PHP_EOL; //通过不可逆算法生成哈希值,无法通过密文反推原始内容,常用于用户密码存储

echo md5_file("006_string.php") . PHP_EOL;
echo sha1_file("006_string.php") . PHP_EOL;

echo strrev("leyland") . PHP_EOL; //字符串反转

echo str_repeat("leyland", 3) . PHP_EOL; //重复字符串

echo str_shuffle("leyland") . PHP_EOL; //随机打乱字符串

echo str_word_count("leyland yao") . PHP_EOL; //统计单词数

echo var_dump(str_split("leyland", 2)); //字符串转数组,每两个分为一组

echo implode("-", ["leyland", "yao"]) . PHP_EOL; //数组转字符串
echo var_dump(explode(" ", "leyland yao")); //字符串转数组

$str1 = "<abc>";
$str2 = "<© W3CSçh°°¦§>";
echo htmlentities($str1) . PHP_EOL; //将正常状态下的字符转换为html中的特殊字符
echo html_entity_decode($str2) . PHP_EOL; //将html中的特殊字符转换正常状态下的字符

$str = "This is some <b>bold</b> text.";
echo htmlspecialchars($str) . PHP_EOL; //将正常状态下的字符转换为html中的特殊字符
echo htmlspecialchars_decode("This is some <b>bold</b> text.") . PHP_EOL; //将html中的特殊字符转换正常状态下的字符
// 和上面的功能类似,但是只能处理 & " ' < > 这几个字符

echo strip_tags("<p>This is some <b>bold</b> text.</p>") . PHP_EOL; //去除html标签

#addslashes会给字符串中默认加转义字符\
#addslashes 转义字符范围‌:仅处理以下 4 种字符:
#单引号 ' → \'
#双引号 " → \"
#反斜杠 \ → \\
#NULL 字符(\0) → \\0

echo addslashes("It's your job") . PHP_EOL; //
echo addslashes('He said "Hello!"');

echo addcslashes("Hello World!", "W") . PHP_EOL; //在指定字符前添加反斜杠

echo stripcslashes("Hello \Wor\ld!") . PHP_EOL; //去除反斜杠,并且还会解析反斜杠如 \b \t等
echo stripslashes("hew\t\bc") . PHP_EOL; //去除反斜杠,会解析\t

echo chr(65) . PHP_EOL; //ASCII码转字符
echo ord("A") . PHP_EOL; //字符转ASCII码

echo bin2hex("Hello World!") . PHP_EOL; //将字符串的每个字符转换为对应的 ‌2 位十六进制 ASCII 码‌
echo hex2bin("48656c6c6f20576f726c6421") . PHP_EOL; //将有效的2 位十六进制 ASCII 码‌字符串转换回普通字符串

echo crc32("Hello World!") . PHP_EOL; //计算字符串的 32 位 CRC(循环冗余校验)码

 

posted @ 2025-04-27 13:56  黑山老猫  阅读(8)  评论(0)    收藏  举报