Chapter 8 String Processing_PHP Tutorial
Note: The article comes from Li Yanhui’s PHP video tutorial. This article is for communication only and may not be used for commercial purposes, otherwise you will be responsible for the consequences.
Learning points:
1. String formatting
2. Substring operations
3. String comparison
4. Find and replace strings
5. Processing Chinese characters
In daily programming work, processing, adjusting and finally controlling strings is an important part. It is generally believed that
this is the basis of all programming languages. Unlike other languages, PHP doesn't bother using data types to handle strings. This way, string manipulation in PHP couldn't be easier.
1. String formatting
The first step to clean up a string is to clean up the extra spaces in the string. Although this operation is not required, it is useful if is saving the string to a file or database, or comparing it to other strings.
The chop() function removes excess whitespace after the string, including new lines.
The ltrim() function removes excess white space at the beginning of the string.
The rtrim() function removes excess whitespace after the string, including new lines. This function is an alias of chop().
The trim() function removes excess whitespace on both sides of a string.
<?<span php </span><span echo</span> <span trim</span>(' PHP '<span ); </span>?>
. The
nl2br() function takes a string as an input parameter and replaces the newline character in the string with the
tag in XHTML.
<?<span php </span><span echo</span> <span nl2br</span>("This is a Teacher!\nThis is a Student!"<span ); </span>?>
If you want to remove HTML from a string, you can use the strip_tags() function
<?<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> ?>
may cause some problems because the database will interpret these characters as control characters. These problematic characters are quotation marks (single quotation mark
and double quotation mark), backslash () and NULL characters.
PHP provides two functions specifically for escaping strings. Before writing any strings to the database, they should
be reformatted using addslashes().
After calling addslashes(), all quotes have slashes added and stripslashes() function removes them. these slashes.
<?<span php </span><span echo</span> <span addslashes</span>('This is \a" Teacher! '<span ); </span>?>
strtoupper() function converts the string to uppercase
strtolower() function converts the string to lowercase
ucfirst() function converts the first letter to uppercase
ucwords() function converts each letter to uppercase Convert the first letter of words to uppercase
<?<span php </span><span echo</span> <span strtoupper</span>('yc60.com@gmail.com'<span ); </span>?>
<?<span php </span><span echo</span> <span str_pad</span>('Salad',10).'is good.'<span ; </span>?>
2. Manipulate substrings
Often, we want to look at individual parts of a string. For example, look at words in a sentence, or split a domain name or email address into its component parts. PHP provides several string functions to achieve this functionality.Use the functions explode(), implode() and join()
To implement this functionality, the first function we will use is explode().
Use the implode() or join() function to achieve the opposite effect of the function explode(). The effects of these two functions are
consistent.
<?<span php </span><span $email</span> = 'yc60.com@gmail.com'<span ; </span><span $email_array</span> = <span explode</span>('@',<span $email</span><span ); </span>?>
word from a string at a time, the strtok() function works better than the explode() function.
<?<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>?>
Decompose the string: str_split() returns an array, where each array element is a character
<?<span php </span><span echo</span> <span substr</span>("abcdef", 1, 3<span ); </span>?>
Reverse a string: strrev() can reverse a string.
<?<span php </span><span print_r</span>(<span str_split</span>('This is a Teacher!'<span )); </span>?>
<?<span php </span><span echo</span> <span strrev</span>('This is a Teacher!'<span ); </span>?>
So far, we have used the "==" sign to compare two strings for equality. Some more complex comparisons can be performed using PHP. These comparisons fall into two categories: partial matches and other cases. String sorting: strcmp(), strcasecmp() and strnatcmp()
This function requires two parameter strings for comparison. This function returns 0 if the two strings are equal, a positive number if is lexicographically behind str1 and str2 (greater than str2), and a negative
number if str1 is less than str2. This function is case-sensitive.
The function strcasecmp() is the same as strcmp() except that it is not case sensitive.
The function strnatcmp() and the corresponding case-insensitive strnatcasecmp() function are new in PHP4.
These two functions compare strings according to "natural sorting". The so-called natural sorting is to sort in the order that people are accustomed to.
<?<span php </span><span echo</span> <span strcmp</span>('a','b'<span ); </span>?>
使用strspn()函数返回一个字符串中包含有另一个字符串中字符的第一部分的长度。也
就是求两个字符串之间相同的部分。
<?<span php </span><span echo</span> <span strspn</span>('gmail','yc60.com@gmail.com'<span ); </span>?>
使用strlen()函数测试字符串的长度
可以使用函数strlen()来检查字符串的长度。如果传给它一个字符串,这个函数将返回
字符串的长度。例如, strlen("hello") 将返回5.
<?<span php </span><span echo</span> <span strlen</span>('This is a Teacher!'<span ); </span>?>
确定字符串出现的频率:substr_count()返回一个字符串在另一个字符串中出现的次数。
<?<span php </span><span echo</span> <span substr_count</span>('yc60.com@gmail.com','c'<span ); </span>?>
四.查找替换字符串
通常,我们需要检查一个更长的字符串中是否含有一个特定的子字符串。这种部分匹配
通常比测试字符串的完全等价更有用处。
在字符串中查找字符串:strstr()、strchr()、strrchr()和stristr()
函数strstr()是最常见的,它可以用于在一个较长的字符串专供查找匹配的字符串或字
符。请注意,函数strchr()和strstr()完全一样。
<?<span php </span><span echo</span> <span strstr</span>('yc60.com@gmail.com','@'<span ); </span>?>
函数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>?>
替换字符串: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>?>
五.处理中文字符
对于以上的字符串函数,有些可以用于中文,但有些却不适用中文。所以,PHP 提供
了专门的函数来解决这样的问题。
中文字符可以是gbk,utf8,gb2312
mb_strlen() 对应的函数为strlen() 求字符串的长度
mb_strstr() 对应的函数为strstr() 求某字符串到结尾的字符
mb_strpos() 对应的函数为strpos() 求出字符最先出现处
mb_substr() 对应的函数为substr() 取出指定的字符串
mb_substr_count() 对应函数为substr_str() 返回字符串出现的次数
最后扫一遍帮助手册

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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.

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? 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. 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? 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,

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.

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
