SoFunction
Updated on 2025-03-10

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

0x01: Perform lexical analysis of strings based on predefined characters

Copy the codeThe code is as follows:

<?php
/*
* Regular expression functions can greatly slow down when processing large amounts of information. These functions should be used when you need to parse complex strings using regular expressions. If you want to parse simple expressions, you can also use many predefined functions that can significantly speed up the processing process.
 */

/*
* Perform lexical analysis of strings based on predefined characters
* The strtok() function parses strings based on a predefined list of characters. Its form is:
 * string strtok(string str,string tokens)
* The strtok() function must be called continuously to completely analyze a string; each time the function is called, it is only a lexical analysis of the next part of the string. However, the str parameter needs to be specified only once, because the function will track the position in str, knowing that the lexical analysis of str has been completely completed, or the experience str parameter is specified.
* As shown in the following example:
 */
$info="lv chen yang|Hello:world&757104454@";
//Define the delimiter, including (|)(:)( )(&)
$tokens="|:& ";
$tokened=strtok($info, $tokens);
while ($tokened)
{
 echo "Element:$tokened<br/>";
//Continuously call strtok() function to complete the lexical analysis of the entire string
 $tokened=strtok($tokens);
}
?>

0x02: Decompose strings based on predefined delimiters

Copy the codeThe code is as follows:

<?php
/*
* Decompose strings based on predefined delimiters: exploit() function
* The subfunction divides the string str into a substring 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 the separator. The number of elements can be limited by the optional parameter limit. You can combine exploit()/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 PHP series.
   I discuss the many improvements and addtions to
   <a href=\"http:\">PHP</a> object-oriented architecture.
   ";
echo "<br/>";
$words=explode(' ', strip_tags($summary));
echo "This sentence's lenght is:".sizeof($words);
/*
* The exploit() function is always much faster than preg_split, spilt() and spliti(). Therefore, when you do not need to use regular expressions, be sure to use this function.
 */
?>

0x03: Convert array to string

Copy the codeThe code is as follows:

<?php
/*
* Convert array to string
* The exploit() function can convert a string into a corresponding array based on the defined characters, but the array can be converted into a string with the specified defined characters as a boundary through the implode() function.
* Its form is:
 * 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

Copy the codeThe code is as follows:

<?php
/*
* Parsing complex strings
* The strpos() function finds the first occurrence of substr in a case-sensitive manner in a string, and its form is
 * int strpos(string str,string substr [,int offset])
* Optional parameter offset specifies the location where the search starts. If substr is not in str, strpos() returns False. Optional parameters determine where strpos() starts searching.
* The following example will determine the timestamp for the first access:
 */
$substr="";
$log=<<<logfile
192.168.1.1:/www/htdocs/:[2013/06/26:13:25:10]
192.168.1.2:/www/htdocs/:[2013/06/26:13:27:16]
192.168.1.3:/www/htdocs/:[2013/06/26:13:28:45]
logfile;
echo "<br/>";
//What is the first time $substr appears in the log
$pos=strpos($log, $substr);
// Find the value position at the end of the row
$pos1=strpos($log,"\n",$pos);
// Calculate the start of the timestamp
$pos=$pos+strlen($substr)+1;
//Retrieve timestamp
$timestamp=substr($log, $pos,$pos1-$pos);
echo "The file was first accessed on: $timestamp<br/>";
/*
* The function stripos() and function strpos() have the same usage, the only difference is that stripos() is case-sensitive.
 */
?>

0x05: Find the last occurrence of the string

Copy the codeThe code is as follows:

<?php
/*
* Find the last occurrence of the string
* strrpos() function searches for the last occurrence of a string, and returns its position (numerical number) and its form is:
 * int strrpos(string str,char substr [,offset])
* Optional parameter offset determines the starting search position of the strrpos() function. Add to the news summary that hopes to shorten the lengthy
* Intercept some parts of the summary and replace the cut off with ellipses. However, it is not simply to cut the summary clearly to the required length,
* You may want to cut in a user-friendly way to cut 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 PHP series.
   I discuss the many improvements and addtions to
   <a href=\"http:\">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

Copy the codeThe code is as follows:

<?php
/*
* Replace all instances of a string with another string
* str_replace() function uses another string to fantasize all instances of a string in a case-sensitive manner. Its form 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 the count currency in str is replaced.
* This function is very suitable for hiding the electronic right-click address for programs that automatically obtain email addresses, as shown below:
 */
$email="lvchenyang@";
$email=str_replace("@", "(at)", $email);
echo "<br/>".$email;
?>

0x07: Get part of the string

Copy the codeThe code is as follows:

<?php
/*
* Get part of the string
* strstr() function returns the remaining part of the string starting from the first occurrence of the predefined string (including the occurrence string). Its form is:
 * string strstr(string str,string occurrence[,bool fefore_needle])
* The optional parameter before_needle will change the behavior of strstr(), causing the function to return the part of the string before the first.
* The following example is to get the domain name in the right click, combined with the ltrim() function
 */
$url="lvchenyang@";
echo "<br/>".ltrim(strstr($url, "@"),"@");
?>

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

Copy the codeThe code is as follows:

<?php
/*
* The substr() function returns the part of the string between start and start+length, in its form:
 * string substr(string str,int start [,int length])
* If there is no specified optional parameter, return the string from start to end of str
* As shown below
 */
$str="lvchenyang";
echo "<br/>".substr($str, 2,4);
//output: chen
?>

0x09: Determine the frequency of the string occurrence

Copy the codeThe code is as follows:

<?php
/*
* Determine the frequency of the string occurrence
* substr_count() returns the number of times a string appears in another string. Its form is:
 * int substr_count(string str,string substring [,int offset [,int length]])
* Optional parameters offset and length specify the string cheap (try matching strings from cheap places) and string length (length from cheap places)
* The following example determines the number of times each word appears in this sentence
 */
$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 part of a string with another string

Copy the codeThe code is as follows:

<?php
/*
* Replace part of a string with another string
* substr_replace() function replaces part of the string with another string, and the replacement starts from the specified start position and knows that the start+length position ends.
* Its form is:
* The values ​​of stringsubstr_replace(string str, string resumement, int start and length.
* As shown below, replace the 4 digits in the middle of the phone number
 */
$phonenum="15926841384";
echo "<br/>".substr_replace($phonenum, "****", 3,4);
?>