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

  • 2021-08-03 09:44:15
  • OfStack

0x01: Lexical parsing of strings based on predefined characters


<?php
/*
 * When dealing with a large amount of information, regular expression functions can greatly slow down the speed. You should use these functions when you need to use regular expressions to parse complex strings. If you want to parse simple expressions, you can also use many predefined functions that can significantly speed up the processing.
 */ /*
 * Lexical analysis of strings based on predefined characters
 * strtok() Function parses a string based on a predefined list of characters. It takes the form of:
 * string strtok(string str,string tokens)
 * strtok() Function, you must call this function continuously in order to completely match the 1 Lexical analysis of strings; Every time this function is called, it is only the following of the string 1 Part of them do lexical analysis. But ,str Parameters only need to be specified 1 Because the function tracks str In the position, know exactly right str Completed lexical analysis, or specified experience str Parameter.
 * As shown in the following example:
 */
$info="lv chen yang|Hello:world&757104454@qq.com";
// Define delimiters, including (|)(:)( )(&)
$tokens="|:& ";
$tokened=strtok($info, $tokens);
while ($tokened)
{
 echo "Element:$tokened<br/>";
 // Continuous invocation strtok() Function to complete the lexical analysis of the entire string
 $tokened=strtok($tokens);
}
?>

0x02: Decompose string according to predefined delimiter


<?php
/*
 * Decompose the string according to the predefined delimiter: explode() Function
 * The sub-function puts the string str Divided into substring arrays in the form of:
 * array explode(string separator,string str [, int limit])
 * The original string is based on separator The specified string is divided into different elements. The number of elements can be determined by optional parameters limit To limit. Can be combined explode()/sizeof() And strip_tags() To determine the total number of words in a given text block
 * As shown below:
 */
$summary="
   In the latest installment of the ongoing Developer.com PHP series.
   I discuss the many improvements and addtions to
   <a href=\"http:www.php.com\">PHP</a> object-oriented architecture.
   ";
echo "<br/>";
$words=explode(' ', strip_tags($summary));
echo "This sentence's lenght is:".sizeof($words);
/*
 * explode() Function always ratio preg_split , spilt() And spliti() Much faster. Therefore, when regular expressions are not needed, 1 Be sure to use this function.
 */
?>

0x03: Convert Array to String


<?php
/*
 * Convert an array to a string
 * explode() Function can convert a string to an array based on the bounding character, but you can use the implode() Function converts an array to a string bounded by the specified bounding character
 * It takes the form of:
 * string implode(string delimiter,array pieces)
 * As shown below:
 */
$citys=array("Chengdu","Chongqing","Beijing","Shanghai","Guangzhou");
$citystring=implode("|", $citys);
echo $citystring;
?>

0x04: Parsing complex strings


<?php
/*
 * Parsing complex strings
 * strpos() Function is found in a string in a case-sensitive manner substr No. 1 1 The position of the second occurrence, which is in the form of
 * int strpos(string str,string substr [,int offset])
 * Optional parameters offset Specifies where to start the search. If substr Not in str In, then strpos() Return False . Optional parameter determination strpos() Where to start searching.
 * The following example will determine the 1 Second visit index.html Time stamp of:
 */
$substr="index.html";
$log=<<<logfile
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 "<br/>";
//$substr In log What is the first place in the
$pos=strpos($log, $substr);
// Find the numeric position at the end of the row
$pos1=strpos($log,"\n",$pos);
// Start of calculating timestamp
$pos=$pos+strlen($substr)+1;
// Retrieve timestamp
$timestamp=substr($log, $pos,$pos1-$pos);
echo "The file index.html was first accessed on: $timestamp<br/>";
/*
 * Function stripos() And function strpos() Function is used in the same way, only 1 The difference is that stripos() Case-insensitive.
 */
?>

0x05: Find the last occurrence of the string


<?php
/*
 * Find the last in the string 1 The position of the second occurrence
 * strrpos() Function searches for the last occurrence of a string and returns its position (numeric sequence number) in the form:
 * int strrpos(string str,char substr [,offset])
 * Optional parameters offset Determine strrpos() The starting search position of the function. Add a news summary that hopes to shorten the lengthy,
 * Intercept some parts of the summary and replace the truncated parts with ellipsis. However, instead of simply cutting the summary to the required length,
 * You may wish to use 1 Cut in a user-friendly way to the end of the word closest to the stage length.
 * As shown in the following example
 */
$limit=100;
$summary="In the latest installment of the ongoing Developer.com PHP series.
   I discuss the many improvements and addtions to
   <a href=\"http:www.php.com\">PHP</a> object-oriented architecture. ";
if(strlen($summary)>$limit)
 $summary=substr($summary, 0,strrpos(substr($summary, 0,$limit)," "))."...";
echo  $summary;
?>

0x06: Replace all instances of a string with another string


<?php
/*
 * Use another 1 A string replaces all instances of a string
 * str_replace() Function in a case-sensitive manner using another 1 String fantasy all instances of a string. It takes the form of:
 * mixed str_replace(string occurrence, mixed replacement, mixed str [,int count])
 * If str Not found in occurrence , then str If optional parameters are defined, count Replace only the str Medium count A currence .
 * This function is good for hiding the electronic right-click address from programs that automatically obtain e-mail addresses, as shown below:
 */
$email="lvchenyang@live.cn";
$email=str_replace("@", "(at)", $email);
echo "<br/>".$email;
?>

0x07: Gets 1 part of a string


<?php
/*
 * Object of the string 1 Part
 * strstr() Function returns a string from the first of a predefined string 1 The rest of the beginning of the occurrence ( Include occurrence This string ) . It takes the form of:
 * string strstr(string str,string occurrence[,bool fefore_needle])
 * Optional parameters before_needle Will change strstr() Causes the function to return a string in the 1 The part before the first one.
 * The following example is to get the domain name in the right click and combine it with ltrim() Function
 */
$url="lvchenyang@live.cn";
echo "<br/>".ltrim(strstr($url, "@"),"@");
?>

0x08: Returns 1 part of string based on predefined cheapness


<?php
/*
 * substr() Function returns a string that is located in the start And start+length The part between, in the form of:
 * string substr(string str,int start [,int length])
 * If no optional parameters are specified, the start To str End string
 * As shown below
 */
$str="lvchenyang";
echo "<br/>".substr($str, 2,4);
//output: chen
?>

0x09: Determine the frequency of string occurrence


<?php
/*
 * Determine the frequency of string occurrence
 * substr_count() Return 1 Strings in another 1 The number of occurrences in a string. It takes the form of:
 * int substr_count(string str,string substring [,int offset [,int length]])
 * Optional parameters offset And length Specify the string cheapness (try to match the string from the cheapness) and the string length ( Length of search from cheap )
 * The following example determines that each word is in this sentence Number of occurrences in
 */
$talk=<<<talk
I am acertain that we could dominate mindshare in this space with
our new product, extablishing a true synergy beteen the marketing
and product development teams. We'll own this space in thress months.
talk;
echo "<br/>";
$sentencearray=explode(" ", $talk);
foreach ($sentencearray as $item)
{
 echo "The word <strong>$item</strong> appears(".substr_count($talk, $item).")times<br/>";
}
?>

0x10: Replace 1 part of 1 string with another 1 string


<?php
/*
 * Use another 1 String substitution 1 Of a string 1 Part
 * substr_replace() Function sets the 1 Partially use another 1 String replacement, replacing the string from the specified start Position starts, know start+length End of position.
 * It takes the form of:
 * stringsubstr_replace(string str,string repalcement,int start And length The value of.
 * As shown below, replace the middle of the phone number 4 Bit
 */
$phonenum="15926841384";
echo "<br/>".substr_replace($phonenum, "****", 3,4);
?>


Related articles: