Some string operation functions in PHP that can replace regular expression functions

Source: Internet
Author: User
Tags strtok
This article mainly introduces some string operation functions in PHP that can replace regular expression functions. This article summarizes some special string operation functions. For more information, see 0x01: perform lexical analysis on strings based on predefined characters

The code is as follows:


<? Php
/*
* When processing a large amount of information, the regular expression function slows down significantly. These functions should be used only when you need to use regular expressions to parse strings that are more complex. To parse a simple expression, you can also use many predefined functions that can significantly accelerate the processing process.
*/

/*
* Perform lexical analysis on strings based on predefined characters
* The strtok () function parses strings based on the predefined character list. The format is:
* String strtok (string str, string tokens)
* The strtok () function must be called consecutively to perform lexical analysis on a string. each call to this function only performs lexical analysis on the next part of the string. However, the str parameter only needs to be specified once, because the function will track the position in the str, knowing that the lexical analysis is complete for the str, or the str parameter is specified.
* Example:
*/
$ Info = "lv chen yang | Hello: world & 757104454@qq.com ";
// Definition delimiter, including (| )(:)()(&)
$ Tokens = "| :&";
$ Tokened = strtok ($ info, $ tokens );
While ($ tokened)
{
Echo "Element: $ tokened
";
// Call the strtok () function consecutively to perform lexical analysis on the entire string.
$ Tokened = strtok ($ tokens );
}
?>

0x02: break down strings based on predefined delimiters

The code is as follows:


<? Php
/*
* Break down the string: explode () function based on predefined delimiters
* The sub-function divides the str string into a sub-string array in the form:
* Array explode (string separator, string str [, int limit])
* The original string is divided into different elements according to the string specified by separator. The number of elements can be limited by the optional parameter limit. You can combine explode ()/sizeof () and strip_tags () to determine the total number of words in a given text block.
* As follows:
*/
$ Summary ="
In the latest installment of the ongoing pai.com PHP series.
I discuss the role improvements and addtions
PHP object-oriented architecture.
";
Echo"
";
$ Words = explode ('', strip_tags ($ summary ));
Echo "This sentence's lenght is:". sizeof ($ words );
/*
* The explode () function is always much faster than preg_split, spilt (), and spliti. Therefore, you must use this function when you do not need a regular expression.
*/
?>

0x03: convert an array to a string

The code is as follows:


<? Php
/*
* Convert an array to a string.
* The explode () function can convert a string to an array based on the defined characters. However, you can use the implode () function to convert an array to a defined character as a boundary string.
* The format is:
* String implode (string delimiter, array pieces)
* As follows:
*/
$ Citys = array ("Chengdu", "Chongqing", "Beijing", "Shanghai", "Guangzhou ");
$ Citystring = implode ("|", $ citys );
Echo $ citystring;
?>

0x04: parse complex strings

The code is as follows:


<? Php
/*
* Parse complex strings
* The strpos () function finds the position of the first occurrence of a substr in case-sensitive mode in the string, in the form
* Int strpos (string str, string substr [, int offset])
* The optional parameter offset specifies the start position of the search. If substr is not in str, strpos () returns False. The optional parameter determines where strpos () starts searching.
* In the following example, the timestamp of the first batch index.html will be confirmed:
*/
$ Substr = "index.html ";
$ Log = < 192.168.1.1:/www/htdocs/index.html: [2013/06/26: 13: 25: 10]
192.168.1.2:/www/htdocs/index.html: [2013/06/26: 13: 27: 16]
192.168.1.3:/www/htdocs/index.html: [2013/06/26: 13: 28: 45]
Logfile;
Echo"
";
// $ Position where substr first appears in log
$ Pos = strpos ($ log, $ substr );
// Locate the end value of the row
$ Pos1 = strpos ($ log, "\ n", $ pos );
// Start of timestamp calculation
$ Pos = $ pos + strlen ($ substr) + 1;
// Search the timestamp
$ Timestamp = substr ($ log, $ pos, $ pos1-$ pos );
Echo "The file index.html was first accessed on: $ timestamp
";
/*
* The stripos () function and strpos () function have the same usage. The only difference is that stripos () is case insensitive.
*/
?>

0x05: Locate the last occurrence of the string

The code is as follows:


<? Php
/*
* Locate the last position in the string
* The strrpos () function searches for the final position of a string and returns its position (numerical number) in the form:
* Int strrpos (string str, char substr [, offset])
* The optional parameter offset determines the start position of the strrpos () function. Add the news summary to shorten the lengthy period,
* Truncate some parts in the summary and use ellipsis to replace the truncated parts. However, it is not simply to cut the summary clearly into the desired length,
* You may want to cut it in a user-friendly manner and cut it to the end of the word closest to the stage length.
* Example:
*/
$ Limit = 100;
$ Summary = "In the latest installment of the ongoing pai.com PHP series.
I discuss the role improvements and addtions
PHP object-oriented architecture .";
If (strlen ($ summary)> $ limit)
$ Summary = substr ($ summary, 0, strrpos (substr ($ summary, 0, $ limit ),""))."...";
Echo $ summary;
?>

0x06: all instances of the string replaced by another string

The code is as follows:


<? Php
/*
* Replace all instances of strings with another string
* The str_replace () function uses another string to create all instances of a string in a case-sensitive manner. The format is:
* Mixed str_replace (string occurrence, mixed replacement, mixed str [, int count])
* If occurrence is not found in str, str remains unchanged. if the optional parameter count is defined, only count currence in str is replaced.
* This function is suitable for hiding an electronic right-click address for programs that automatically obtain an email address, as shown below:
*/
$ Email = "lvchenyang@live.cn ";
$ Email = str_replace ("@", "(at)", $ email );
Echo"
". $ Email;
?>

0x07: obtain part of a string

The code is as follows:


<? Php
/*
* Obtain part of a string
* The strstr () function returns the rest of the string starting from the first appearance of the predefined string (including the occurrence string ). The format is:
* String strstr (string str, string occurrence [, bool fefore_needle])
* The optional parameter before_needle changes the behavior of strstr () so that the function returns the part of the string before the first exit.
* The following example shows how to get the domain name in the right-click operation and combine it with the ltrim () function.
*/
$ Url = "lvchenyang@live.cn ";
Echo"
". Ltrim (strstr ($ url ,"@"),"@");
?>

0x08: return part of the string based on the predefined cheap

The code is as follows:


<? Php
/*
* The substr () function returns the part of the string between start and start + length in the form:
* String substr (string str, int start [, int length])
* If no optional parameter is specified, the string from start to the end of str is returned.
* As shown below
*/
$ Str = "lvchenyang ";
Echo"
". Substr ($ str, 2, 4 );
// Output: chen
?>

0x09: determine the occurrence frequency of the string

The code is as follows:


<? Php
/*
* Determine the occurrence frequency of a string
* Substr_count () returns the number of times a string appears in another string. The format is:
* Int substr_count (string str, string substring [, int offset [, int length])
* Optional parameter offset and length specify a string that is cheap (attempts to match strings starting from cheap) and string length (the length of searches starting from cheap)
* The following example determines the number of times each word appears in this sentence.
*/
$ Talk = < I am acertain that we coshould dominate mindshare in this space
Our new product, extablishing a true synergy beteen the marketing
And product development teams. We'll own this space in thress months.
Talk;
Echo"
";
$ Sentencearray = explode ("", $ talk );
Foreach ($ sentencearray as $ item)
{
Echo "The word$ ItemAppears (". substr_count ($ talk, $ item).") times
";
}
?>

0x10: replace a part of a string with another string.

The code is as follows:


<? Php
/*
* Replace a part of a string with another string.
* The substr_replace () function replaces a part of the string with another string, starting from the specified start position and knowing that the start + length position ends.
* The format is:
* Stringsubstr_replace (string str, string repalcement, int start and length values.
* Replace the four digits in the middle of the phone number as follows:
*/
$ Phonenum = "15926841384 ";
Echo"
". Substr_replace ($ phonenum," ***** ", 3,4 );
?>

Related Article

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.