在 PHP 中,提供了一系列的系统函数,用于实现字符串的相关操作。
PHP 常用字符串函数:
| 函数名 | 说明 |
|---|---|
| chr() | 从指定ASCII值返回字符 |
| explode() | 分割字符串 |
| ltrim() | 移除字符串左侧的空白字符或其他字符 |
| md5() | 使用MD5算法对字符串进行加密 |
| nl2br() | 将字符串中的\n转换为 |
| ord() | 返回字符串中第一个字符的ASCII值 |
| rtrim() | 移除字符串右侧的空白字符或其他字符 |
| strlen() | 返回字符串长度 |
| str_replace() | 替换字符串中的一些字符(大小写敏感) |
| strpos() | 返回字符串在另一字符串中第一次出现的位置(大小写敏感) |
| strrpos() | 返回字符串在另一字符串中最后一次出现的位置(大小写敏感) |
| strtolower() | 把字符串转换为小写字母 |
| strtoupper() | 把字符串转换为大写字母 |
| substr() | 截取字符串 |
| trim() | 移除字符串两侧的空白字符或其他字符 |
示例
<?phpheader("content-type:text/html;charset=utf-8");$a = explode("-","北京-上海-深圳");echo "分割字符串:";print_r($a);echo "<br/><br/>";$a = strlen("你好中国");echo "字符串长度:{$a}<br/><br/>";$a = md5("张三");echo "md5加密:{$a}<br/><br/>";$a = str_replace("Hello", "你好", "Hello,北京");echo "字符串替换:{$a}<br/><br/>";$a = strtolower("HelloWorld");echo "转为小写字母:{$a}<br/><br/>";$a = strtoupper("HelloWorld");echo "转为大写字母:{$a}<br/><br/>";$a = substr("HelloWorld", 5,5);echo "字符串截取:{$a}<br/><br/>";$a = trim("==中国==","=");echo "移除字符串两侧的其他字符:{$a}<br/><br/>";
file() 函数把整个文件读入一个数组中。
file(path,include_path,context)
| 参数 | 描述 |
|---|---|
| path | 必需。规定要读取的文件。 |
| include_path | 可选。如果也想在 include_path 中搜寻文件的话,可以将该参数设为 “1”。 |
| context | 可选。规定文件句柄的环境。 context 是一套可以修改流的行为的选项。若使用 null,则忽略。 |
<?php printr(file(“test.txt”)); ?>
Array (
[0] => Hello World. Testing testing!
[1] => Another day, another line.
[2] => If the array picks up this line,
[3] => then is it a pickup line? )
file_get_contents() 函数把整个文件读入一个字符串中。
file_get_contents(_path,include_path,context,start,max_length)
| 参数 | 描述 |
|---|---|
| path | 必需。规定要读取的文件。 |
| include_path | 可选。如果也想在 include_path 中搜寻文件的话,可以将该参数设为 “1”。 |
| context | 可选。规定文件句柄的环境。 context 是一套可以修改流的行为的选项。若使用 null,则忽略。 |
| start | 可选。规定在文件中开始读取的位置。该参数是 PHP 5.1 新加的。 |
| max_length | 可选。规定读取的字节数。该参数是 PHP 5.1 新加的。 |
<?php echo file_get_contents(“test.txt”); ?>
This is a test file with test text.
