Home Backend Development PHP Tutorial 处置PHP字符串的10个简单方法

处置PHP字符串的10个简单方法

Jun 13, 2016 pm 01:15 PM
count csv php replace

处理PHP字符串的10个简单方法

PHP处理字符串的能力非常强大,方法也是多种多样,但有的时候你需要选择一种最简单且理想的解决方法。文章列举了10个PHP中常见的字符串处理案例,并提供了相对应的最理想的处理方法。

1.确定一个字符串的长度

这是文章中最明显的一个例子,其中的问题是我们如何来确定一个字符串的长度,这里我们不能不提的就是strlen()函数:

$text = "sunny day"; $count = strlen($text); // $count = 9

2.截取文本,创建一个摘要

新闻性质的网站通常会截取一个大约200字左右的段落,并在次段落的末尾加上省略号来形成一个摘要,这时,你可以使用substr_replace()函数来实现此功能。由于篇幅的原因,这里只演示对40个字符的限制:

$article = "BREAKING NEWS: In ultimate irony, man bites dog.";

$summary = substr_replace($article, "…", 40);

//$summary = "BREAKING NEWS: In ultimate irony, man bi…"

3.计算字符串中的字符和单词数

相信您经常会看到一些博客或者新闻类文章,来总结文章的总字数,或者我们也经常看到一些投稿的要求:在一定的字数范围内。这时,你可以使用str_word_count()函数来计算文章字数的总和:

$article = "BREAKING NEWS: In ultimate irony, man bites dog.";

$wordCount = str_word_count($article); // $wordCount = 8

有的时候你需要更加严格的控制投稿者的使用空间,例如一些批注等等。如果你想知道有多少个字符来组成一个数组,请使用count_chars()函数。

4.解析CSV文件

数据通常是以逗号分隔的形式存储在文件中的(如一个已知的CSV文件),CSV文件使用一个逗号或者类似于预定义符号,将每列字符串组成一个单独的行。你可能经常创建PHP脚本来导入这些数据,或者解析出你所需要的东西,这些年来,我也看到过很多解析CSV文件的方法,最常见的就是使用fgets()和explode()函数的组合来读取和解析文件,然而,最简单的方法是使用一个函数来解决问题,但它并不属于PHP的字符串处理库里的一部分:fgetcsv()函数。使用fopen()和fgetcsv()函数,我们能够很容易的解析这个文件,同时检索出每个联系人的名字:

$fh = fopen("contacts.csv", "r");

while($line = fgetcsv($fh, 1000, ","))

{ echo "Contact: {$line[1]}"; }

5.转换成一个字符串数组

某些时候,你可能需要创建CSV文件,同时又在这些文件中进行读取,这就意味着你需要将那些同逗号分隔的字符串转换成数据。如果这些数据最初是从数据库检索出的,那么它很可能会只给您提供一个数组。这时,您可以使用implode()函数,将这些字符串转换成一个数组:

$csv = implode(",", $record);

6.将网址转换成超链接

目前许多WYSIWYG编辑器提供的工具栏,都允许用户标记文本,包括超链接。但是,当内容呈现到页面上时,你可以很容易的自动执行此过程,同时保证您不出现额外的错误。要转换成超链接的URL,你可以使用preg_replace()函数,它可以按照正则表达式来搜索一个字符串,并定义了URL的结构:

$url = "W.J. Gilmore, LLC (http://www.php100.com)";http://www.php100.com)"

$url = preg_replace("/http://([A-z0-9./-]+)/", "$0", $url);

// $url = "W.J. Gilmore, LLC (

7.从一个字符串中去除HTML标签

作为Web开发人员,其中的一个主要工作就是要确保用户输入中不含有危险字符,如果有,这会导致SQL注入或脚本攻击。PHP语言中包含了很多安全方面的功能,这些功能能够帮助你过滤数据,包括延长过滤器。例如,你可以允许用户中带有一些基本的HTML语句,包括一些注释。实现这个功能,你可以使用带有检查功能函数:strip_tags()。它在默认的情况下是从字符串中删除所有的HTML标签,但同时也允许覆盖默认或者你指定的标签。例如,在下面的例子中,你可以除去所有的标签:

$text = strip_tags($input, "

");

8.比较两个字符串

比较两个字符串,以确保它们是相同的。例如,判断用户第一次与第二次输入的密码是否相同,你可以使用substr_compare()函数来很容易的现实:

$pswd = "secret";

$pswd2 = "secret";

if (! strcmp($pswd, $pswd2))

{ echo "The passwords are not identical!";

}

如果你想判断两个字符串不区分大小写,可以使用strcasecmp()函数。

9.转换换行符

在本文中我介绍了如何轻松转换成超超链接的URL,现在介绍nl2br()函数,这个函数能够帮助你将任何换行符转换成HTML标签。

$comment = nl2br($comment);

10.应用自动换行

应用自动换行,你可以使用PHP中的这个函数:wordwrap():

$speech = "Four score and seven years ago our fathers brought forth, upon this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.";

echo wordwrap($speech, 30);

执行上面的代码,结果是:

Four score and seven years ago our fathers brought forth, upon this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
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)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles