A detailed description of strings and regular expressions in PHP, PHP regular Expressions _php tutorial

Source: Internet
Author: User
Tags php regular expression

A detailed description of the string and regular expressions in PHP, with a detailed description of the PHP regular expression


I. Characteristics of String types

1, PHP is a weakly typed language, other data types can be directly applied to string function operation.

<?php
echo substr ("123456", 2,4); Output 345
echo substr (123456,2,4); Output 345
echo Hello; Look for Hello constants first, and if not found, use Hello as a string
?>

2, the string can be used as an "array", is a collection of characters.

<?php
$str = "Www.jb51.net";
echo $str [0];
echo $str [1];
Echo $str [2];
?>

However, the string is not a true array, and the function of the array cannot be used. such as COUNT ($STR) does not return a string length. The PHP engine cannot differentiate between characters and arrays, resulting in two semantics. Since PHP4, curly braces have been used instead of square brackets.

<?php
To ensure backward compatibility, square brackets can still be used
$str = www.jb51.net;
echo $str {0};
echo $str {1};
echo $str {2};
?>

3. Double quotation mark variable parsing

In PHP, when you define a string with double quotes or delimiters, the variables are parsed.

<?php
$arr = Array (' name ' = = ' Dwqs ', ' add ' = ' www.ido321.com ');
echo "$arr [name]"; Can parse, but cannot use quotation marks in square brackets
echo "$arr [' name ']"; Error
echo "{$arr [' name ']}"; Can parse, with curly braces containing elements, name without quotation marks is also possible
Suppose there is an object $square
echo "$square->width"; Can parse
echo "$square->width00 cent"; Can not parse, with curly braces to solve
echo "{$square->width}width00 cent"; Can parse
?>

Second, the string output function

Iii. commonly used string format functions

Most of the string handling functions of ps:php do not modify the source string, but instead return the new string

Four, the regular expression

The regular expression describes a pattern of string matching, which is composed of three parts: Atomic, meta-character, and pattern modifier, through which the string is matched, searched, replaced, and delimited in a particular function.

In PHP, there are two regular library of processing functions: Pcre and POSIX. The former is named after the Preg_ prefix and is compatible with Perl; the latter is named after the Ereg_ prefix. The two functions are similar, but the efficiency of pcre is slightly higher.

The Perl language-compatible regular expression handler:

1. Grammar

1.1 delimiter: When using patterns in a Perl-compatible regular function, you must add a delimiter to the pattern. Any character other than letters, numbers, and backslashes (\) can be used as a bounding symbol

<?php
The following regularization is legal
echo $m 1 = '/<\/\w+/';
echo $m 2 = ' | (\d{3})-\d| Sm ';
echo $m 3 = '!^ (? i) php[34]! ';
echo $m 4 = ' {^\s+ (\s+)? $} ';
?>

1.2 Atoms: atoms contain ordinary characters, such as letters, numbers, nonprinting characters, such as spaces, carriage returns, special characters and metacharacters characters, such as quotation marks, *, +, etc., must be escaped with "\"; custom atomic tables such as [APJ], [A-z], universal character types, such as \d, \d.

<?php
The following are equivalent, matching e-mail
$mail 1 = '/^[0-9a-za-z]+@[0-9a-za-z]+ (\.[ 0-9a-za-z]+) {0,3}$/';
$mail 2 = '/^\w+@\w+ (\.\w+) {0,3}$/';
?>

1.3 Metacharacters: A character that is used to construct a regular expression with a special meaning. Perl can use a variety of meta-characters to search for matches, such as *, +,? Common meta characters are as follows

1.4 mode modifier: Used outside the regular delimiter, extending the function of the regular in matching, replacing, and so on.

2. perl-compatible regular expression functions

2.1 Preg_match (String pattern,string Subject[,array matches]): Used to find and match strings. Parameter description:

Pattern is a regular, subject is a string that needs to be processed, an optional matches is used to match the results of each sub-pattern stored in pattern, matches[0] preserves the overall content that matches the pattern, matches[1] Preserves the matching content in the first parenthesis in pattern, and so on.

<?php
Header ("Content-type:text/html;charset=utf8");
$pattern = '/(HTTP): \/\/(WWW) \. ([^\.\/]+)\. (com|net|org)/I ';
$subject = "My blog: http://www.ido321.com";
if (Preg_match ($pattern, $subject, $matches)) {
echo "Search URL is:". $matches [0]. "
"; The 1th element of the array holds the entire matching result
The protocol in the Echo "URL is:". $matches [1]. "
";//the 2nd element of the array holds the 1th-word expression
The host in the echo "URL is:". $matches [2]. "
";//the 3rd element of the array holds the 2nd-word expression
The domain name in the echo "URL is:". $matches [3]. "
";//the 4th element of the array holds the 3rd-word expression
The top field in the echo "URL is:". $matches [4]. "
";//the 5th element of the array holds the 4th-word expression
}
?>

Results

Preg_match_all () is similar to the Preg_match () function, where the former is matched to the end of the string, which stops matching after the first match.

2.2 Preg_grep (String Pattern,array iput): Matches an element in an array, returning an array cell that matches a regular match. Parameter description:

pattern is regular, and input is an array that needs to be matched.

<?php
$arr = Array (' Linux RedHat9.0 ', ' Apache2.2.9 ', ' MySQL5.0.51 ', ' PHP5.2.6 ', ' LAMP ', ' 100 ');
$version = Preg_grep ('/^[a-za-z]+ (\d|\.) +$/', $arr);
Output: Array ([1]=>apache2.2.9 [2]=>mysql5.0.51 [3]=>php5.2.6]

?>

2.3 preg_replace (mixed pattern,mixed replacement,mixed subject[,int limit]): string substitution. Description

The function searches the subject for a match with pattern and replaces it with replacement. Limit is used to restrict the number of matches, that is, the number of replacements.

<?php
$pattern = '/<[\/\!] *? [^<>]*?/is ';
$text = ' This text is bold and underlined and Italic ';
Echo preg_replace ($pattern, "", $text); Replace all HTML tags with an empty
Echo preg_replace ($pattern, "", $text, 2); Value replaces first 2 HTML tags
?>

2.4 preg_split (String pattern,string subject[,int Limit[,int flags]): Splits the string. Description

The function returns an array. The array element contains a string that is split in subject with the pattern match as the boundary, and the limit means see 2.3,flags meaning refer to the documentation.

<?php
Split a string by any number of spaces
$kerwords = Preg_split ("/[\s,]+/", "hypertext Language,programming");
Output: Array ([0]=>hypertext [1]=>language,[2[=>programming]
Print_r ($kerwords);
?>

PHP Regular expression + string extraction problem

$str = ' {"A": 1234567890, "B": "U", "Birthday": "2000-01-01", "Gender": "1", "Location": "123456", "Login_ip": " 123.123.123.123 "," login_time ": 1234567890," id ":" 1234567 "," sign ":" 0bcbdea54d1f2c3c75b058eb5d2ae124 "} ';
$user _id= "";
if (Preg_match_all (' | ') ID ":" (\s+?) "|", $str, $reg))
{
$user _id= $reg [1][0];
}
echo "UserID is:". $user _id;
?>

Output Result:
UserID is:1234567

How do you use regular expressions to add content to a string in PHP?

You can use regular expressions, or directly with PHP, feel or PHP is more convenient:
$str = Str_replace ("

http://www.bkjia.com/PHPjc/898289.html www.bkjia.com true http://www.bkjia.com/PHPjc/898289.html techarticle PHP string and regular expressions in detail, the PHP regular expression of one, the character string type 1, PHP is a weak type language, other data types can be applied directly to the string ...

  • 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.