Home Backend Development PHP Tutorial Chapter 8 String Processing_PHP Tutorial

Chapter 8 String Processing_PHP Tutorial

Jul 13, 2016 am 10:34 AM
aspnet software programming

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>?>
Copy after login
PHP has a series of functions available for reformatting strings, and these functions work in different ways

. 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>?>
Copy after login
To convert special characters to their HTML equivalent, you can use the htmlentities() and htmlspecialchars functions.

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>
?>
Copy after login
For strings, certain characters are definitely valid, but when inserting data into the database,

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>?>
Copy after login
You can reformat the case of letters in a string.

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>?>
Copy after login
Fill string function: str_pad() fills the string with the specified number of characters.

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

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.

Use the strtok() function
<?<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
The strtok() function only takes out some fragments (called tokens) from the string at a time. For processing one

word from a string at a time, the strtok() function works better than the explode() function.

Using the substr() 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>?>
Copy after login
The function substr() allows us to access a substring of a given start and end point of a string. This function is not suitable for our example, but it can be very useful when you need to get a part of a fixed format string.



Decompose the string: str_split() returns an array, where each array element is a character

string in the string parameter.
<?<span php
</span><span echo</span> <span substr</span>("abcdef", 1, 3<span );
</span>?>
Copy after login


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>?>
Copy after login

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

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>?>
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() 返回字符串出现的次数

最后扫一遍帮助手册

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/748764.htmlTechArticle注:文章出自李炎恢PHP视频教程,本文仅限交流使用,不得用于商业用途,否则后果自负。 学习要点: 1.字符串格式化 2.操作子字符串 3...
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,

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.

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

See all articles