Examples of various php string processing methods

Source: Internet
Author: User
PHP can process strings in a variety of ways, but sometimes you need to select the simplest and ideal solution. This article lists 10 common cases of string processing in PHP and provides the most ideal processing method. 1. determine the length of a string. this is the most obvious SyntaxHighlighter in the article. all (); PHP can process strings in a variety of ways, but sometimes you need to choose the simplest and ideal solution. This article lists 10 common cases of string processing in PHP and provides the most ideal processing method.

1. determine the length of a string
This is the most obvious example in the article. The question here is how to determine the length of a string. what we cannot but mention here is the strlen () function:

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

2. extract text and create a summary
News websites usually take a section about 200 characters and add a ellipsis at the end of the section to form a summary. in this case, you can use substr_replace () function. Due to the length of the article, only the limit of 40 characters is demonstrated here:

$ Article = "breaking news: In ultimate irony, man bites dog .";

$ Summary = substr_replace ($ article, "...", 40 );

// $ Summary = "breaking news: In ultimate irony, man bi ..."

3. calculate the number of characters and words in a string.
I believe that you will often see blog or news articles to summarize the total number of words in the article, or we often see some requirements for contribution: within a certain word range. In this case, you can use the str_word_count () function to calculate the total number of words in the article:

$ Article = "breaking news: In ultimate irony, man bites dog .";

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

Sometimes you need to strictly control the space used by contributors, such as comments. If you want to know the number of characters to form an array, use the count_chars () function.

4. parse CSV files
Data is usually stored in a file (such as a known CSV file) in a comma separated form. the CSV file uses a comma or is similar to a predefined symbol, separate each column of strings into a single row. You may often create PHP scripts to import the data or parse what you need. over the years, I have seen many methods to parse CSV files, the most common is to use a combination of fgets () and explode () functions to read and parse files. However, the simplest way is to use a function to solve the problem, but it is not part of the PHP string processing library: fgetcsv () function. Using the fopen () and fgetcsv () functions, we can easily parse this file and retrieve the name of each contact at the same time:

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

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

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

5. convert to a string array
In some cases, you may need to create CSV files and read them at the same time, which means you need to convert the strings separated by commas into data. If the data is first retrieved from the database, it may only provide you with an array. In this case, you can use the implode () function to convert these strings into an array:

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

6. convert a URL into a hyperlink
Currently, many WYSIWYG editors provide toolbar that allow users to mark text, including hyperlinks. However, when the content is displayed on the page, you can easily perform this process automatically without any additional errors. To convert a URL to a hyperlink, you can use the preg_replace () function to search for a string based on a regular expression and define the URL structure:

$ 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. remove HTML tags from a string
As a Web developer, one of the main tasks is to ensure that user input does not contain any dangerous characters. if so, this will lead to SQL injection or script attacks. PHP includes many security features that help you filter data, including extended filters. For example, you can allow users to include some basic HTML statements, including some annotations. To implement this function, you can use the function strip_tags () with the check function (). By default, it deletes all HTML tags from the string, but it also allows to overwrite the default or tag you specified. For example, in the following example, you can remove all labels:

$ Text = strip_tags ($ input ,"

");

8. compare two strings
Compare two strings to make sure they are the same. For example, you can use the substr_compare () function to determine whether the password you entered is the same for the first and second times:

$ Pswd = "secret ";

$ Pswd2 = "secret ";

If (! Strcmp ($ pswd, $ pswd2 ))

{Echo "The passwords are not identical! ";

}

If you want to judge whether two strings are case-insensitive, you can use the strcasecmp () function.

9. line feed conversion
This article describes how to easily convert a URL to a hyperlink. now we will introduce the nl2br () function, which can help you convert any line break into an HTML tag.

$ Comment = nl2br ($ comment );

10. automatic application line feed
Automatically wrap the application. you can use this function in 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 );

Run the above code and the result is:

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.