0. PHP&HTML混写
- 99乘法表的显示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<table>
<?php
for ($i=1; $i <=9; $i++) { ?>
<tr>
<?php
for ($j=1; $j <= $i ; $j++) {
$ret = $i * $j;
?>
<td style="border: 1px solid blue">
<?php echo "$j * $i = $ret" ?>
</td>
<?php } ?>
<?php } ?>
</table>
</body>
</html>
— 数组展示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<?php
$stus = [
["name"=>"Tom", "age"=>24, "gender"=>"male", "address"=>"Beijing"],
["name"=>"Jack", "age"=>26, "gender"=>"male", "address"=>"Beijing"],
["name"=>"Rose", "age"=>42, "gender"=>"male", "address"=>"Beijing"],
["name"=>"Tony", "age"=>21, "gender"=>"male", "address"=>"Beijing"],
];
?>
<table>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>地址</th>
</tr>
<?php foreach($stus as $stu){ ?>
<tr>
<?php
foreach($stu as $val){ ?>
<td>
<?php echo $val; ?>
</td>
<?php } ?>
</tr>
<?php } ?>
</table>
</body>
</html>
1. 字符串操作
一个字符串 string 就是由一系列的字符组成,其中每个字符等同于一个字节。如果是汉字,根据编码计算所占字节数.
2. 定符串定义
- 单引号形式
``` // 不转义,所见即所得 $s1 = ‘hello’;
$s2 = ‘hello $s1 \n’;
- 双引号形式
```php
// 转义变量或转义特殊字符
$s1 = "hello";
$s2 = "hello $s1 \n";
3. 获取字符串长度函数
strlen() -返回给定的字符串
string
的长度。strlen(string $string): int
<?php
header("content-type:text/html;charset=utf8");
$s1 = "helloworld";
echo strlen($s1);
echo "<br>";
$s2 = "你好";
echo strlen($s2);
echo "<br>";
?>
4. 查找相关
strpos() — 查找字符串首次出现的位置
strpos(string $haystack, mixed $needle, int $offset = 0): int
<?php
header("content-type:text/html;charset=utf8");
// 可查找单个字符
$s1 = "helloworld";
echo strpos($s1,"o");
echo "<br>";
// 可查多个字符
$s2 = "哈喽你好你好";
echo strpos($s2, "你");
echo "<br>";
echo strpos($s2, "你好");
echo "<br>";
?>
strrpos() — 计算指定字符串在目标字符串中最后一次出现的位置, 反向查找;
strrpos(string $haystack, string $needle, int $offset = 0): int
<?php
header("content-type:text/html;charset=utf8");
// 可查找单个字符
$s1 = "helloworld";
echo strrpos($s1,"o");
echo "<br>";
// 可查多个字符
$s2 = "哈喽你好你好";
echo strrpos($s2, "你");
echo "<br>";
echo strrpos($s2, "你好");
echo "<br>";
?>
stripos() — 查找字符串首次出现的位置(不区分大小写)
stripos(string $haystack, string $needle, int $offset = 0): int
<?php
header("content-type:text/html;charset=utf8");
// 可查找单个字符
$s1 = "heLloworld";
echo stripos($s1,"l");
echo "<br>";
?>
strripos() — 计算指定字符串在目标字符串中最后一次出现的位置(不区分大小写)
strripos(string $haystack, string $needle, int $offset = 0): int
<?php
header("content-type:text/html;charset=utf8");
// 可查找单个字符
$s1 = "heLloworld";
echo strripos($s1,"l");
echo "<br>";
?>
5. 统计相关
str_word_count — 返回字符串中单词的使用情况
format参数:
指定函数的返回值。当前支持的值如下:str_word_count(string $string, int $format = 0, ?string $characters = null): array|int
- 0 - 返回单词数量(默认)
- 1 - 返回一个包含
string
中全部单词的数组 - 2 - 返回关联数组。数组的键是单词在
string
中出现的数值位置索引下标,数组的值是这个单词
注意:请注意,不支持多字节编码的字符串(不支持汉字统计)。
<?php
header("content-type:text/html;charset=utf8");
$str = "Hello fri3nd, you're
looking good today!";
echo str_word_count($str);
echo "<br>";
print_r(str_word_count($str, 0));
echo "<br>";
print_r(str_word_count($str, 1));
echo "<br>";
print_r(str_word_count($str, 2));
?>
substr_count — 计算字串出现的次数
substr_count(
string $haystack,
string $needle,
int $offset = 0,
?int $length = null
): int
```php <?php header(“content-type:text/html;charset=utf8”); $text = ‘This is a test’;
// 查找全部字符串内容 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’); ?>
<a name="a2cc5f9d"></a>
#### 6. 比较相关
- [strcmp](https://www.php.net/manual/zh/function.strcmp.php) — 二进制安全字符串比较<br />如果 `str1` 小于 `str2` 返回 < 0; 如果 `str1` 大于 `str2` 返回 > 0;如果两者相等,返回 0。(返回值为两串相减的差值)
```php
strcmp(string $str1, string $str2): int
<?php
header("content-type:text/html;charset=utf8");
echo strcmp("a", "b");
echo "<br>";
echo strcmp("a", "a");
echo "<br>";
echo strcmp("b", "a");
echo "<br>";
echo strcmp("abc", "z");
echo "<br>";
?>
strcasecmp — 二进制安全比较字符串(不区分大小写)
如果str1
小于str2
返回 < 0; 如果str1
大于str2
返回 > 0;如果两者相等,返回 0。strcasecmp(string $str1, string $str2): int
<?php
header("content-type:text/html;charset=utf8");
echo strcasecmp("a", "b");
echo "<br>";
echo strcasecmp("a", "a");
echo "<br>";
echo strcasecmp("b", "a");
echo "<br>";
echo strcasecmp("abc", "z");
echo "<br>";
echo strcasecmp("A", "a");
echo "<br>";
echo strcasecmp("ab", "Z");
echo "<br>";
?>
strncmp — 二进制安全比较字符串开头的若干个字符
该函数与 strcmp() 类似,不同之处在于你可以指定两个字符串比较时使用的长度(即最大比较长度)。
注意该比较区分大小写。strncmp(string $str1, string $str2, int $len): int
<?php
header("content-type:text/html;charset=utf8");
echo strncmp("abcc", "abcd", 3);
echo "<br>";
?>
7. 替换相关
str_replace — 子字符串替换
str_replace(
mixed $search,
mixed $replace,
mixed $subject,
int &$count = ?
): mixed
```php <?php header(“content-type:text/html;charset=utf8”);
// 替换不会改变原字符串,会生成一个新字符串 $old = “aa”; $new = “AA”; $str = “aaBBaaBBaaBB”; $newStr = str_replace($old, $new, $str); echo $str; echo “
“; echo $newStr; echo “
“;// 查找值可以是字符串,也可以是数组 // 将字符串中所有出现的元音使用空串替换掉 // 赋值: Hll Wrld f PHP $vowels = array(“a”, “e”, “i”, “o”, “u”, “A”, “E”, “I”, “O”, “U”); $onlyconsonants = str_replace($vowels, “”, “Hello World of PHP”); echo $onlyconsonants; echo “
“;// 当查找值和替换值都使用数组,则值会一一对应替换, // 赋值: You should eat pizza, beer, and ice cream every day $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); echo $newphrase; echo “
“;// 赋值: 2 $str = str_replace(“ll”, “”, “good golly miss molly!”, $count); echo $count; echo “
“; echo $str;
?>
- [str_ireplace](https://www.php.net/manual/zh/function.str-ireplace.php) — str_replace 的忽略大小写版本
```php
str_ireplace(
mixed $search,
mixed $replace,
mixed $subject,
int &$count = ?
): mixed
<?php
header("content-type:text/html;charset=utf8");
// 替换不会改变原字符串,会生成一个新字符串
$old = "aa";
$new = "--";
$str = "aaBBAABBaaBBAABB";
$newStr = str_ireplace($old, $new, $str);
echo $str;
echo "<br>";
echo $newStr;
echo "<br>";
?>
str_repeat — 重复一个字符串
str_repeat(string $input, int $multiplier): string
<?php
header("content-type:text/html;charset=utf8");
echo str_repeat("Hello", 5);
echo "<br>";
?>
substr_replace — 替换字符串的子串(根据指定的位置 进行替换)
substr_replace() 在字符串string
的副本中将由start
和可选的length
参数限定的子字符串使用replacement
进行替换。substr_replace(
mixed $string,
mixed $replacement,
mixed $start,
mixed $length = ?
): mixed
```php $var = ‘ABCDEFGH:/MNRPQR/‘; echo “Original: $var
\n”;
/ 这两个例子使用 “bob” 替换整个 $var。/
echo substr_replace($var, ‘bob’, 0) . “
\n”;
echo substr_replace($var, ‘bob’, 0, strlen($var)) . “
\n”;
/ 将 “bob” 插入到 $var 的开头处。/
echo substr_replace($var, ‘bob’, 0, 0) . “
\n”;
/ 下面两个例子使用 “bob” 替换 $var 中的 “MNRPQR”。/
echo substr_replace($var, ‘bob’, 10, -1) . “
\n”;
echo substr_replace($var, ‘bob’, -7, -1) . “
\n”;
/ 从 $var 中删除 “MNRPQR”。/
echo substr_replace($var, ‘’, 10, -1) . “
\n”;
<a name="75be37d2"></a>
#### 8. 转换相关
- [chr](https://www.php.net/manual/zh/function.chr.php) — 返回指定的字符
```php
chr(int $ascii): string
<?php
echo "48 - >" . chr(48) . "<br>";
echo "65 - >" . chr(65) . "<br>";
echo "97 - >" . chr(97) . "<br>";
?>
ord — 转换字符串第一个字节为 0-255 之间的值
ord(string $string): int
<?php
echo "0 - >" . ord("0") . "<br>";
echo "A - >" . ord("A") . "<br>";
echo "a - >" . ord("a") . "<br>";
echo "ab - >" . ord("ab") . "<br>"; // 只转换字符串的第一个字符
?>
ucfirst — 将字符串的首字母转换为大写
ucfirst(string $str): string
```php <?php $foo = ‘hello world!’; $foo = ucfirst($foo); // Hello world!
$bar = ‘HELLO WORLD!’; $bar = ucfirst($bar); // HELLO WORLD! $bar = ucfirst(strtolower($bar)); // Hello world! ?>
- [ucwords](https://www.php.net/manual/zh/function.ucwords.php) — 将字符串中每个单词的首字母转换为大写
```php
ucwords(string $str, string $delimiters = " \t\r\n\f\v" ): string
<?php
$foo = 'hello world!';
$foo = ucwords($foo); // Hello World!
echo $foo . "<br>";
$foo = 'HELLO WORLD!';
$foo = ucwords($foo); // HELLO WORLD!
$foo = ucwords(strtolower($foo)); // Hello World!
echo $foo . "<br>";
$foo = 'hello|world!';
$foo = ucwords($foo); // Hello|world!
echo $foo . "<br>";
$foo = ucwords($foo, "|"); // Hello|World!
echo $foo . "<br>";
?>
- lcfirst — 使一个字符串的第一个字符小写
```php <?php $foo = ‘HelloWorld’; $foo = lcfirst($foo); // helloWorldlcfirst(string $str): string
$bar = ‘HELLO WORLD!’; $bar = lcfirst($bar); // hELLO WORLD! $bar = lcfirst(strtoupper($bar)); // hELLO WORLD! ?>
- [strtolower](https://www.php.net/manual/zh/function.strtolower.php) — 将字符串转化为小写
```php
strtolower(string $string): string
<?php
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = strtolower($str);
echo $str; // 打印 mary had a little lamb and she loved it so
?>
strtoupper — 将字符串转化为大写
strtoupper(string $string): string
<?php
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = strtoupper($str);
echo $str; // 打印 MARY HAD A LITTLE LAMB AND SHE LOVED IT SO
?>
strip_tags — 从字符串中去除 HTML 和 PHP 标记
strip_tags(string $str, string $allowable_tags = ?): string
<?php
$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
echo strip_tags($text);
// 允许 <p> 和 <a>
echo strip_tags($text, '<p><a>');
?>
str_shuffle — 随机打乱一个字符串
str_shuffle(string $str): string
<?php
$s = "Hello World";
echo $s . "<br>";
echo str_shuffle($s);
?>
htmlspecialchars — 将特殊字符转换为 HTML 实体
htmlspecialchars(
string $string,
int $flags = ENT_COMPAT | ENT_HTML401,
string $encoding = ini_get("default_charset"),
bool $double_encode = true
): string
| 字符 | 替换后 | | —- | —- | |
&
(& 符号) |&
| |"
(双引号) |"
,除非设置了**ENT_NOQUOTES**
| |'
(单引号) | 设置了**ENT_QUOTES**
后,'
(如果是**ENT_HTML401**
) ,或者'
(如果是**ENT_XML1**
、**ENT_XHTML**
或**ENT_HTML5**
)。 | |<
(小于) |<
| |>
(大于) |>
|
<?php
$s = "<a href='test'>Test</a>";
$new = htmlspecialchars($s, ENT_QUOTES);
echo $new; // <a href='test'>Test</a>
echo "<br>";
echo $s;
?>
9. 分割连接
substr — 返回字符串的子串
substr(string $string, int $offset, ?int $length = null): string
<?php
echo substr("abcdef", 3) . "<br>"; // 返回 "def"
echo substr("abcdef", 0, -1) . "<br>"; // 返回 "abcde"
echo substr("abcdef", 2, -1) . "<br>";; // 返回 "cde"
echo substr("abcdef", 4, -4) . "<br>";; // 返回 ""; 在 PHP 8.0.0 之前,返回 false
echo substr("abcdef", -3, -1) . "<br>";; // 返回 "de"
?>
str_split — 将字符串转换为数组
str_split(string $string, int $split_length = 1): array
<?php
$str = "Hello Friend";
$arr1 = str_split($str);
$arr2 = str_split($str, 3);
print_r($arr1);
print_r($arr2);
?>
explode — 使用一个字符串分割另一个字符串
explode(string $separator, string $string, int $limit = PHP_INT_MAX): array
<?php
// 示例 1
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo '<br>';
echo $pieces[1]; // piece2
echo '<br>';
// 示例 2
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
$arr = explode(":", $data);
var_dump($arr);
?>
implode — 将一个一维数组的值转化为字符串
implode(string $glue, array $pieces): string
implode(array $pieces): string
```php <?php $array = array(‘lastname’, ‘email’, ‘phone’);
echo implode($array); echo ‘
‘;echo implode(“,”, $array); echo ‘
‘;echo implode(“—“, $array); echo ‘
‘;// Empty string when using an empty array: var_dump(implode(‘hello’, array())); // string(0) “”
?>
- [join](https://www.php.net/manual/zh/function.join.php) — 别名 implode
- [strstr](https://www.php.net/manual/zh/function.strstr.php) — 查找字符串的首次出现, 返回 `haystack` 字符串从 `needle` 第一次出现的位置开始到 `haystack` 结尾的字符串。
```php
<?php
header("content-type:text/html;charset=utf8");
$s = "Hello php hello mysql";
echo strstr($s, "hello");
echo "<br>";
echo strstr($s, "php");
echo "<br>";
?>
stristr — strstr 函数的忽略大小写版本
<?php
header("content-type:text/html;charset=utf8");
$s = "Hello php hello mysql";
echo stristr($s, "hello");
echo "<br>";
echo stristr($s, "php");
echo "<br>";
?>
strchr — 别名 strstr
10. 去除空白
ltrim — 删除字符串开头的空白字符(或其他字符)
<?php
header("content-type:text/html;charset=utf8");
$s1 = " hello world ";
echo "|" . $s1 . "|";
echo "<br>";
echo "|" . ltrim($s1) . "|";
echo "<br>";
?>
rtrim — 删除字符串末端的空白字符(或者其他字符)
<?php
header("content-type:text/html;charset=utf8");
$s1 = " hello world ";
echo "|" . $s1 . "|";
echo "<br>";
echo "|" . rtrim($s1) . "|";
echo "<br>";
?>
trim — 去除字符串首尾处的空白字符(或者其他字符)
<?php
header("content-type:text/html;charset=utf8");
$s1 = " hello world ";
echo "|" . $s1 . "|";
echo "<br>";
echo "|" . trim($s1) . "|";
echo "<br>";
?>
11. 加密
- md5 — 计算字符串的 MD5 散列值
<?php
header("content-type:text/html;charset=utf8");
$s1 = "heLloworld";
echo $s1;
echo "<br>";
echo md5($s1);
echo "<br>";
?>
12. 反转字符串
- strrev — 反转字符串
<?php
header("content-type:text/html;charset=utf8");
$s1 = "heLloworld";
echo $s1;
echo "<br>";
echo strrev($s1);
echo "<br>";
?>
13. 序列化 serialize()
serialize() 返回字符串,此字符串包含了表示 value
的字节流,可以存储于任何地方。
这有利于存储或传递 PHP 的值,同时不丢失其类型和结构。
serialize(mixed $value): string
基本使用
<?php
// 序列化数组
$animals = ["chicken", "duck", "goose",'dog','pig'];
$aniStr = serialize($animals);
echo $aniStr;
echo "<br>";
// 序列化复杂数组
$animals = ["chicken", "duck", "goose",'dog','pig',100,true,[1,2,3]];
$aniStr = serialize($animals);
echo $aniStr;
echo "<hr>";
// 基本数据类型也可以进行序列化,但一般没必要
echo serialize(100) . "<br>"; //i:100;
echo serialize(3.14) . "<br>"; //d:3.140000000000000124344978758017532527446746826171875;
echo serialize(true) . "<br>"; //b:1;
echo serialize(false) . "<br>"; //b:0;
echo serialize("hello") . "<hr>"; //s:5:"hello";
?>
序列化原理
```php <?php function mySerialize($data){ $s = “;”;// 用来保存序列化字符串的变量
$retS = “”;
// 获取类型
$t = gettype($data);
// 根据不同的类型进行不同形式的拼接
switch($t){
// 整数类型
case "integer":
$retS .= "i:" . $data;
break;
// 小数类型
case "double":
$retS .= "d:" . $data;
break;
// 布尔类型
case "boolean":
$v = $data?"1":"0";
$retS .= "b:" . $v;
break;
// 字符串类型
case "string":
$l = strlen($data);
$retS .= "s:{$l}:" . "\"$data\"";
break;
// 数组类型
case "array":
$retS .= "a:" . count($data) . ":{";
foreach ($data as $key => $value) {
$retS .= mySerialize($key);
$retS .= mySerialize($value);
}
$retS .= "}";
// 数组后面不拼接分号
$s = "";
break;
} return $retS . $s; }
echo mySerialize(100) . “
“; //i:100;
echo mySerialize(3.14) . “
“; //d:3.140000000000000124344978758017532527446746826171875;
echo mySerialize(true) . “
“; //b:1;
echo mySerialize(false) . “
“; //b:0;
echo mySerialize(“hello”) . “
“; //s:5:”hello”;
// 序列化复杂数组
$animals = [“chicken”, “duck”, “goose”,’dog’,’pig’,100,3.14,true,[1,2,3]];
$aniStr = mySerialize($animals);
echo $aniStr;
echo “
“; ?>
<a name="15958dae"></a>
#### 14. 反序列化
**unserialize()** 对单一的已序列化的变量进行操作,将其转换回 PHP 的值。
```php
unserialize(string $str): mixed
序列化数据
i:100;
d:3.14;
b:1;
b:0;
s:5:"hello";
a:9:{i:0;s:7:"chicken";i:1;s:4:"duck";i:2;s:5:"goose";i:3;s:3:"dog";i:4;s:3:"pig";i:5;i:100;i:6;b:1;i:7;a:3:{i:0;i:1;i:1;i:2;i:2;i:3;}i:8;s:3:"php";}
反序列化
<?php
$file = fopen("test.txt","r");
do{
$content = fgets($file);
$data = unserialize($content);
var_dump($data);
}while($content);
fclose($file);
echo "<hr>";