Summary of common PHP strings based on (to be continued) _php tips

Source: Internet
Author: User
Tags array to string explode first string getdate html tags strcmp strtok urlencode
1. Partitioning and merging
Implode:
Echo Implode (",", Array (' LastName ', ' email ', ' phone '));//Array to string

Explode
Print_r (Explode (",", ' Lastname,email,phone '));//String to array

Split
Print_r (Split ("[/.-]", "2008-9.12"))///or. Or-any symbol to cut into an array

Str_split:
Print_r (Str_split ("Hello Friend", 1))//Cut the string

Preg_split:
Regular split
$ops = Preg_split ("{[+*/-]}", "3+5*9/2");
Print_r ($ops);//return: Array ([0] => 3 [1] => 5 [2] => 9 [3] => 2)

Http_build_query:
Request string after url-encoded is generated
$data = Array (' localhost ' => ' AA ',
' User ' => ' BB ',
' Password ' => ' cc ');
echo Http_build_query ($data);//return: LOCALHOST=AA&USER=BB&PASSWORD=CC

Strtok
Cut a string into small segments
$string = "This Is\tan example\nstring";
Echo strtok ($string, "\n\t");//return: This is
Echo ' Echo strtok ("\n\t"); When the second time returns: an example
Echo ' Echo strtok ("\n\t"); When the third time returns: string
2. Find and replace
Many of the strings are r: Take the Last, I: case-insensitive
echo $pos = Strpos (' abcdef abcdaef ', ' a '); The position of the first occurrence of the letter A, case-sensitive
echo $pos = Strrpos (' abcdef abcdeaf ', ' a '); The position of the last occurrence of the letter A, case-sensitive
Stripos: Case-insensitive
Strripos: Case-insensitive
echo strstr (' user@exa@mple.com ', ' @ ');//return: @exa @mple.com
STRISTR: Case-insensitive
echo strchr (' user@exa@mple.com ', ' @ ');//return: @exa @mple.com
STRRCHR: Then returns: @mple. com,

Preg_grep:
Returns the array cells that match the pattern
$food = Preg_grep ("/^p/", Array ("Apple", "Orange", "Pip", "banana"));
Print_r ($food); Back: Array ([2] => PIP)

STRTR:
Replaces the found string with the specified array
$arr = Array ("www" => "ftp", "Yahoo" => "Baidu");
Echo strtr ("www.yahoo.com", $arr);//return: ftp.baidu.com
Echo strtr ("www.yahoo.com", "Wo", "SX");//return: SSS.YAHXX.CXM translation string Replace all w with S to replace all o with X

STRSPN:
To find the length of the first part.
Echo strspn ("ABCDEFG", "1234567890");//return: 0
To find the length of the first part that is not aligned.
Echo strcspn ("ABCDEFG", "1234567890");//return: 7


3. Regular
Preg_match:
Returns the number of times the pattern was matched. Either 0 times (no match) or 1 times, because Preg_match () stops the search after the first match.
if (Preg_match ("/php/i", "PHP is the Web scripting language of choice."))
echo "Existence";
Else
echo "does not exist";

Preg_match_all:
Instead, it will search until the end of the subject.
Preg_match_all ("/\" ( \d{3})? (? (1) [\-\s]) \d{3}-\d{4}/x ",
"Call 555-1212 or 1-800-555-1212", $phones);
Print_r ($phones [0]);/get all the phone numbers

Ereg_replace:
URL Replace with a super connection
Echo ereg_replace ("[: alpha:]]+://[^<>[:space:]]+[[:alnum:]/]",
"<a href=\" \\0\ ">\\0</a>", ' This is Baidu http://www.baidu.com website. ');
Preg_replace: Filtration
$search = Array ("' <script[^>]*?>.*?</script> ' si",//Remove JavaScript
"' <[\/\!] *? [^<>]*?> ' Si ',//Remove HTML tags
"' ([\ r \ n]) [\s]+ '],//remove white space characters
"' & (quot| #34); ' I ",//Replace HTML entity
"' & (amp| #38); ' I ",
"' & (lt| #60); ' I ",
"' & (gt| #62); ' I ",
"' & (nbsp| #160); ' I ",
"' & (iexcl| #161); ' I ",
"' & (cent| #162); ' I ",
"' & (pound| #163); ' I ",
"' & (copy| #169); ' I ",
"' &# (\d+); '                    E "); Run as PHP code
$replace = Array ("",
"",
"\\1",
"\"",
"&",
"<",
">",
" ",
Chr (161),
Chr (162),
Chr (163),
Chr (169),
"Chr (\\1)");
echo $text = Preg_replace ($search, $replace, ' <b>test</b><script>alert ("ADFASDF");</script> ');

Preg_quote:
Escapes the regular expression character, adding each plus \, in accordance with the regular formula.
Echo Preg_quote (' $ For a g3/400 ', '/');//return: \$40 for a g3\/400

Sql_regcase:
Produces a regular expression for a case-insensitive match

Echo sql_regcase ("Foo-bar.a"); return: [FF][OO][OO]-[BB][AA][RR]. [Aa]

4.URL encoding processing function
UrlEncode:
echo $str = UrlEncode (' http://www.baidu.com?key= Baidu ');//Encoding
echo UrlDecode ($STR);//decoding

Rawurlencode:
A sequence with a percent semicolon (%) followed by a two-digit hexadecimal number is replaced with a literal character
Note: Rawurldecode () will not decode the plus sign (' + ') to a space, while UrlDecode () can.
echo $str = Rawurlencode (' http://www.baidu.com?key= Baidu ');//Encoding
echo Rawurldecode ($STR);

Parse_url:
Resolves the URL and returns its components
Print_r (Parse_url ("Http://username:password@hostname/path?arg=value#anchor"));

PARSE_STR:
is to parse the URL into a variable
$str = "id=1&name=2";
Parse_str ($STR);
Echo $name;
When there is a second argument, the value is stored in the array
$str = "id=1&name=2";
Parse_str ($str, $array);
Print_r ($array);

5. Time function
Mktime
Convert a date to a time stamp
Echo Time ()-mktime (0,0,0,9,17,2008);//returns: Current and September 17, 2008 difference.
echo Date (' y-m-d h:i:s ');/current date and time

GetDate
Get Date/Time information
Print_r (GETDATE (Time ()));
6. Compare
Similar_text:
Compare the similarity of two strings
$a = "Hellohhh6";
$b = "hello3hh";
Echo similar_text ($a, $b);//return: 6 compare the corresponding position with the number of identical characters
echo "<br>";
Similar_text ($a, $b, $similar);
echo $similar. " %"; Output percent of the same character

Soundex
Compare the pronunciation of two words
$a = "DdHello6";
$b = "Hello3";
Echo soundex ($a). " <br> ";
Echo Soundex ($b). " <br> ";
if (Soundex ($a) ==soundex ($b)) echo "sounds the same"; else echo ' different ';

STRNATCMP ():
String comparisons by natural sorting method
$arr = Array ("A1.jpg", "a2.jpg", "a3.jpg", "a4.jpg");
$max = $arr [0];
for ($i =0; $i <count ($arr); $i + +)
{
if (strnatcmp ($arr [$i], $max) >0)
$max = $arr [$i];
}
echo $max;/return: A4.jpg

strcmp
case-sensitive, string comparison by Byte, the first string greater than the second string returns: 1, equal to return: 0, less than return:-1
echo strcmp (' abc ', ' abc ');
STRCASECMP:
Returns the number of differences between two strings
echo strcasecmp (' WBC ', ' BBC ');//return: 21
strncmp
A string comparison of the number of characters specified, this function is similar, and, unlike, you can specify the number of characters to use to compare strings. If any string is shorter than Len, the length of that string is used to compare the
echo strncmp ("Adrdvark", "Aardwolf", 4);//return: 1

7. Sorting
Sort
Rearrange the values of an array by a-Z
$a = Array ("1", "s", "3", "N", "5");//return: 1,3,5,n,s
Sort ($a);//sorted print_r ($a);


8. Other
Str_pad:
The padding string becomes the specified length, Pad_type can be str_pad_right, str_pad_left, or Str_pad_both
Echo Str_pad ("www.yahoo.com", "_", str_pad_both);//String fill function __www.yahoo.com__
strlen ("AAA");//Find the length of the array return: 3
Strrev ()//inversion of string
Strtolower ()//convert to lowercase
Strtoupper ()//Convert to uppercase
Str_replace () replaces strings, case-sensitive str_ireplace () is case-insensitive
Ucfirst ()//Convert first letter to uppercase
Ucwords ()//converts the first letter of each word to uppercase
echo Join ("&", Array (' Wo ', ' Men ', ' Shi '));//String Connection return: Wo&men&shi & Connection

Count_chars:
Returns information about the characters used in a string
Print_r (Count_chars ("Hellohhh6", 0))//Returns the number of occurrences of each byte value (0~255) in the string as an array of values. 0 list all of the. 1 columns appear more than 0 times. 2 column occurrences equal to 0. 3 Returns a string that consists of the byte values used. such as: 6Hehlo. 4 returns a string consisting of the unused byte values
Str_replace:
Str_replace ("Yahoo", "Baidu", "www.yahoo.com");
$c = "www.yahoo.com";
$arr = Array ("yahoo", "com");
Echo Str_replace ($arr, "Baidu", $c);//return: Www.baidu.baidu

$c = "www.yahoo.com";
$arr 1 = Array ("www", "yahoo", "com");
$arr 2 = Array ("FTP", "Baidu", "net");
Echo Str_replace ($arr 1, $arr 2, $c);//return: Ftp.baidu.net

substr ($a, 2,2);//Fetch substring
Echo Substr_count (' This is a test ', ' is ');//Count substring occurrences
Substr_replace ()//Replace substring

$url = "http://localhost/zheng_ze_biao_da/youxiang.php";
Echo substr ($url, Strrpos ($url, "/") +1)//return: Youxiang.php used to return the file name

Str_word_count:
$a = "i/love/you/";
echo Str_word_count ($a);//return: 3 count the number of words in a string
Print_r (Str_word_count ($a, 1));//return: Array ([0] => I [1] => love [2] => for you
Print_r (Str_word_count ($a, 2));//return: Array ([0] => I [3] => Love [9] => for you
Print_r (Str_word_count ($a, 1, "/")); returns: Array ([0] => i/[1] => love/[2] => you/) Here is the Ignore "/"

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.