Home php教程 php手册 第八章 字符串处理

第八章 字符串处理

Jun 13, 2016 am 09:39 AM
aspnet software programming

注:文章出自李炎恢PHP视频教程,本文仅限交流使用,不得用于商业用途,否则后果自负。

学习要点:
1.字符串格式化
2.操作子字符串
3.字符串比较
4.查找替换字符串
5.处理中文字符

 

在每天的编程工作中,处理、调整以至最后控制字符串是很重要的一部分,一般也认为
这是所有编程语言的基础。不同与其他语言,PHP 没有那么麻烦地使用数据类型来处理字
符串。这样一来,PHP 中的字符串处理就再容易不过了。

 

一.字符串格式化

整理字符串的第一步是清理字符串中多余的空格。虽然这一部操作不是必需的,但如果
要将字符串存入一个文件或数据库中,或者将它和别的字符串进行比较,这就是非常有用的。
chop()函数移除字符串后面多余的空白,包括新行。
ltrim()函数移除字符串起始处多余空白。
rtrim()函数移除字符串后面多余的空白,包括新行,此函数是chop()的别名。
trim()函数移除字符串两边多余的空白。

<?<span php
</span><span echo</span> <span trim</span>('        PHP       '<span );
</span>?>
Copy after login

PHP 具有一系列可供使用的函数来重新格式化字符串,这些函数的工作方式是各不相
同的。
nl2br()函数将字符串作为输入参数,用XHTML 中的
标记代替字符串中的换行符。

<?<span php
</span><span echo</span> <span nl2br</span>("This is a Teacher!\nThis is a Student!"<span );
</span>?>
Copy after login

将特殊字符转换为HTML 等价形式,可以使用htmlentities()和htmlspecialchars 函数。
如果想要去掉字符串中的HTML 去掉,可以使用strip_tags()函数

<?<span php
</span><span echo</span> <span htmlentities</span>('<strong>我是吴祁!</strong>'); <span //</span><span 转换所有字符</span>
<span echo</span> <span htmlspecialchars</span>('<strong>我是吴祁!</strong>') <span //</span><span 转换特殊字符</span>
<span echo</span> <span strip_tags</span>('<strong>我是吴祁!</strong>') <span //</span><span 去掉了<strong></span>
?>
Copy after login

对于字符串来说,某些字符肯定是有效的,但是当将数据插入到数据库中的时候可能会
引起一些问题,因为数据库会将这些字符解释成控制符。这些有问题的字符就是引号(单引
号和双引)、反斜杠(\)和NULL 字符。
PHP 提供了两个专门用于转义字符串的函数。在将任何字符串写到数据库之前,应该
使用addslashes()将它们重新格式化,
在调用了addslashes()后,所有的引号都加了斜杠,而stripslashes()函数去掉了这些斜杠。

<?<span php
</span><span echo</span> <span addslashes</span>('This is \a" Teacher! '<span );
</span>?>
Copy after login

可以重新格式化字符串中的字母大小写。
strtoupper()函数将字符串转换为大写
strtolower()函数将字符串转换成小写
ucfirst()函数将第一个字母转换为大写
ucwords()函数将每个单词第一个字母转换为大写

<?<span php
</span><span echo</span> <span strtoupper</span>('yc60.com@gmail.com'<span );
</span>?>
Copy after login

填充字符串函数:str_pad()将字符串用指定个数的字符填充字符串。

<?<span php
</span><span echo</span> <span str_pad</span>('Salad',10).'is good.'<span ;
</span>?>
Copy after login

二.操作子字符串

通常,我们想查看字符串的各个部分。例如,查看句子中的单词,或者将一个域名或电
子邮件地址分割成一个个的组件部分。PHP 提供了几个字符串函数来实现此功能。
使用函数explode()、implode()和join()
为了实现这个功能,我们将使用的第一个函数是explode()。
使用implode()或join()函数来实现与函数explode()相反的效果,这两个函数的效果是一
致的。

<?<span php
</span><span $email</span> = 'yc60.com@gmail.com'<span ;
</span><span $email_array</span> = <span explode</span>('@',<span $email</span><span );
</span>?>
Copy after login

使用strtok()函数
strtok()函数一次只从字符串取出一些片段(称为令牌)。对于一次从字符串中取出一个
单词的处理来说,strtok()函数比explode()函数的效果更好。

<?<span php
</span><span $str</span> = "I,will.be#back"<span ;
</span><span $tok</span> = <span strtok</span>(<span $str</span>,",.#"<span );
</span><span while</span>(<span $tok</span><span ) {
</span><span   echo</span> "<span $tok</span><br \>"<span ;
  </span><span $tok</span> = <span strtok</span>(",.#"<span );
}
</span>?>
Copy after login

使用substr()函数
函数substr()允许我们访问一个字符串给定起点和终点的子字符串。这个函数并不适用
于我们的例子中,但是,当需要得到某个固定格式字符串中的一部分时,它会非常有用。

<?<span php
</span><span echo</span> <span substr</span>("abcdef", 1, 3<span );
</span>?>
Copy after login

分解字符串:str_split()返回一个数组,其中各数组元素分别是字符串参数中的一个字符
串。

<?<span php
</span><span print_r</span>(<span str_split</span>('This is a Teacher!'<span ));
</span>?>
Copy after login

逆置字符串:strrev()可以将一个字符串逆反过来。

<?<span php
</span><span echo</span> <span strrev</span>('This is a Teacher!'<span );
</span>?>
Copy after login

三.字符串比较

到目前为止,我们已经用过"= ="号来比较两个字符串是否相等。使用PHP 可以进行一
些更复杂的比较。这些比较分为两类:部分匹配和其他情况。
字符串的排序:strcmp()、strcasecmp()和strnatcmp()
该函数需要两个进行比较的参数字符串。如果这两个字符串相等,该函数返回0,如果
按字典顺序str1 和str2 后面(大于str2)就返回一个正数,如果str1 小于str2 就返回一个负
数。这个函数是区分大小写的。
函数strcasecmp()除了不区分大小写之外,其他和strcmp()一样。
函数strnatcmp()及与之对应的不区分大小写的strnatcasecmp()函数是在PHP4 中新增的。
这两个函数按“自然排序”比较字符串,所谓自然排序是按人们习惯的顺序进行排序。

<?<span php
</span><span echo</span> <span strcmp</span>('a','b'<span );
</span>?>
Copy after login

使用strspn()函数返回一个字符串中包含有另一个字符串中字符的第一部分的长度。也
就是求两个字符串之间相同的部分。

<?<span php
</span><span echo</span> <span strspn</span>('gmail','yc60.com@gmail.com'<span );
</span>?>
Copy after login

使用strlen()函数测试字符串的长度
可以使用函数strlen()来检查字符串的长度。如果传给它一个字符串,这个函数将返回
字符串的长度。例如, strlen("hello") 将返回5.

<?<span php
</span><span echo</span> <span strlen</span>('This is a Teacher!'<span );
</span>?>
Copy after login

确定字符串出现的频率:substr_count()返回一个字符串在另一个字符串中出现的次数。

<?<span php
</span><span echo</span> <span substr_count</span>('yc60.com@gmail.com','c'<span );
</span>?>
Copy after login

四.查找替换字符串

通常,我们需要检查一个更长的字符串中是否含有一个特定的子字符串。这种部分匹配
通常比测试字符串的完全等价更有用处。
在字符串中查找字符串:strstr()、strchr()、strrchr()和stristr()
函数strstr()是最常见的,它可以用于在一个较长的字符串专供查找匹配的字符串或字
符。请注意,函数strchr()和strstr()完全一样。

<?<span php
</span><span echo</span> <span strstr</span>('yc60.com@gmail.com','@'<span );
</span>?>
Copy after login

函数strstr()有两个变体。第一个变体是stristr(),它几乎和strstr()一样,其区别在于不区
分字符大小。对于我们的只能表单应用程序来说,这个函数非常有用,因为用户可以输入
"delivery"、"Delivery"和"DELIVERY"。
第二个变体是strrchr(),它也几乎和strstr()一样,只不过是strstr()的别名。
查找字符串的位置:strpos()、strrpos()。
函数strpos()和strrpos()的操作和strstr()类似,但它不是返回一个子字符串,而返回子字
符串needle 在字符串haystack 中的位置。更有趣的是,现在的PHP 手册建议使用strpos()
函数代替strstr()函数来查看一个子字符串在一个字符串中出现的位置,因为前者的运行速度

更快。

<?<span php
</span><span echo</span> <span strrpos</span>('yc60.com@gmail.com','c'<span );
</span>?>
Copy after login

替换字符串:str_replace()、str_ireplace()、substr_replace()

<?<span php
</span><span echo</span> <span str_replace</span>('@','#','yc60.com@gmail.com'<span );
</span><span echo</span> <span substr_replace</span>('yc60.com@gmail.com','###',0,5<span );
</span>?>
Copy after login

五.处理中文字符

对于以上的字符串函数,有些可以用于中文,但有些却不适用中文。所以,PHP 提供
了专门的函数来解决这样的问题。
中文字符可以是gbk,utf8,gb2312
mb_strlen() 对应的函数为strlen() 求字符串的长度
mb_strstr() 对应的函数为strstr() 求某字符串到结尾的字符
mb_strpos() 对应的函数为strpos() 求出字符最先出现处
mb_substr() 对应的函数为substr() 取出指定的字符串
mb_substr_count() 对应函数为substr_str() 返回字符串出现的次数

最后扫一遍帮助手册

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The combination of Vue.js and ASP.NET provides tips and suggestions for performance optimization and expansion of web applications. The combination of Vue.js and ASP.NET provides tips and suggestions for performance optimization and expansion of web applications. Jul 29, 2023 pm 05:19 PM

The combination of Vue.js and ASP.NET provides tips and suggestions for performance optimization and expansion of web applications. With the rapid development of web applications, performance optimization has become an indispensable and important task for developers. As a popular front-end framework, Vue.js combined with ASP.NET can help us achieve better performance optimization and expansion. This article will introduce some tips and suggestions, and provide some code examples. 1. Reduce HTTP requests The number of HTTP requests directly affects the loading speed of web applications. pass

MySQL connection pool usage and optimization techniques in ASP.NET programs MySQL connection pool usage and optimization techniques in ASP.NET programs Jun 30, 2023 pm 11:54 PM

How to correctly use and optimize the MySQL connection pool in ASP.NET programs? Introduction: MySQL is a widely used database management system that features high performance, reliability, and ease of use. In ASP.NET development, using MySQL database for data storage is a common requirement. In order to improve the efficiency and performance of database connections, we need to correctly use and optimize the MySQL connection pool. This article will introduce how to correctly use and optimize the MySQL connection pool in ASP.NET programs.

Ten ways generative AI will change software development Ten ways generative AI will change software development Mar 11, 2024 pm 12:10 PM

Translator | Reviewed by Chen Jun | Chonglou In the 1990s, when people mentioned software programming, it usually meant choosing an editor, checking the code into the CVS or SVN code base, and then compiling the code into an executable file. Corresponding integrated development environments (IDEs) such as Eclipse and Visual Studio can integrate programming, development, documentation, construction, testing, deployment and other steps into a complete software development life cycle (SDLC), thus improving the work of developers. efficiency. In recent years, popular cloud computing and DevSecOps automation tools have improved developers' comprehensive capabilities, making it easier for more enterprises to develop, deploy and maintain software applications. Today, generative AI is the next generation development

How to reconnect to MySQL in ASP.NET program? How to reconnect to MySQL in ASP.NET program? Jun 29, 2023 pm 02:21 PM

How to reconnect to MySQL in ASP.NET program? In ASP.NET development, it is very common to use the MySQL database. However, due to network or database server reasons, the database connection may sometimes be interrupted or time out. In this case, in order to ensure the stability and reliability of the program, we need to re-establish the connection after the connection is disconnected. This article will introduce how to reconnect MySQL connections in ASP.NET programs. To reference the necessary namespaces first, reference them at the head of the code file

The combination of Vue.js and ASP.NET enables the development and deployment of enterprise-level applications The combination of Vue.js and ASP.NET enables the development and deployment of enterprise-level applications Jul 29, 2023 pm 02:37 PM

The combination of Vue.js and ASP.NET enables the development and deployment of enterprise-level applications. In today's rapidly developing Internet technology field, the development and deployment of enterprise-level applications has become more and more important. Vue.js and ASP.NET are two technologies widely used in front-end and back-end development. Combining them can bring many advantages to the development and deployment of enterprise-level applications. This article will introduce how to use Vue.js and ASP.NET to develop and deploy enterprise-level applications through code examples. First, we need to install

How to correctly configure and use MySQL connection pool in ASP.NET program? How to correctly configure and use MySQL connection pool in ASP.NET program? Jun 29, 2023 pm 12:56 PM

How to correctly configure and use MySQL connection pool in ASP.NET program? With the development of the Internet and the increase in data volume, the demand for database access and connections is also increasing. In order to improve the performance and stability of the database, connection pooling has become an essential technology. This article mainly introduces how to correctly configure and use the MySQL connection pool in ASP.NET programs to improve the efficiency and response speed of the database. 1. The concept and function of connection pooling. Connection pooling is a technology that reuses database connections. At the beginning of the program,

Recommended configuration for ASP.NET development using Visual Studio on Linux Recommended configuration for ASP.NET development using Visual Studio on Linux Jul 06, 2023 pm 08:45 PM

Overview of the recommended configuration for using Visual Studio for ASP.NET development on Linux: With the development of open source software and the popularity of the Linux operating system, more and more developers are beginning to develop ASP.NET on Linux. As a powerful development tool, Visual Studio has always occupied a dominant position on the Windows platform. This article will introduce how to configure VisualStudio for ASP.NE on Linux

What are the built-in objects in aspnet? What are the built-in objects in aspnet? Nov 21, 2023 pm 02:59 PM

The built-in objects in ASP.NET include "Request", "Response", "Session", "Server", "Application", "HttpContext", "Cache", "Trace", "Cookie" and "Server.MapPath": 1. Request, indicating the HTTP request issued by the client; 2. Response: indicating the HTTP response returned by the web server to the client, etc.

See all articles