Php preg match numbers. PHP regexp: regular expression examples


This article provides a selection of php regexp examples. A very nice and useful collection of examples of regular expressions. All regex examples are acceptable for PHP. Use it to your health!

Domain name verification example

This php snippet checks if the string is a valid domain name.

?:. *) +):? (d +)? /? / i ", $ url)) (echo" Your url is ok. ";) else (echo" Wrong url. ";)

An example of highlighting a word in the text

A very useful regular expression for finding and highlighting the desired word in the text. The code is especially useful when generating search results output.

$ text = "Sample sentence from KomunitasWeb, regex has become popular in web programming. Now we learn regex. According to wikipedia, Regular expressions (abbreviated as regex or regexp, with plural forms regexes, regexps, or regexen) are written in a formal language that can be interpreted by a regular expression processor "; $ text = preg_replace ("/ b (regex) b / i", " 1", $ text); echo $ text;

An example of how to highlight search results forWordPress

Open the search.php file and find the the_title () function. Replace it with the following line:

Echo $ title;

Now, before the replaced line, paste this code:

\0", $ title);?>

Save your search.php file and open style.css. Add the following line to it:

Strong.search-excerpt (background: yellow;)

An example of getting images fromHTML regexp method

This piece of php code using regular expressions, searches all images and url to them.

$ images = array (); preg_match_all ("/ (img | src) = (" | ") [^" ">] + / i", $ data, $ media); unset ($ data); $ data = preg_replace ("/ (img | src) (" | "| =" | = ") (. *) / i", "$ 3", $ media); foreach ($ data as $ url) ($ info = pathinfo ($ url); if (isset ($ info ["extension"])) (if (($ info ["extension"] == "jpg") || ($ info ["extension"] == "jpeg") || ($ info ["extension"] == "gif") || ($ info ["extension"] == "png")) array_push ($ images, $ url);))

Remove duplicate words (case insensitive)

Are there often words that are repeated? Then an example of this regular expression will be useful to you.

$ text = preg_replace ("/ s (w + s) 1 / i", "$ 1", $ text);

Removing Duplicate Points

The same thing, only with repeating dots.

$ text = preg_replace ("/.+/ i", ".", $ text);

XML / HTML tag matching

This simple function takes two arguments: the tag (which you want to match), the xml, or the html code.

Function get_tag ($ tag, $ xml) ($ tag = preg_quote ($ tag); preg_match_all ("(<".$tag."[^>]*>(.*?). ")", $ xml, $ matches, PREG_PATTERN_ORDER); return $ matches; )

Search for XHTML / XML tags with specific attribute values

This example is similar to the previous function, only you can significantly expand the search for example find

.

Function get_tag ($ attr, $ value, $ xml, $ tag = null) (if (is_null ($ tag)) $ tag = "\ w +"; else $ tag = preg_quote ($ tag); $ attr = preg_quote ($ attr); $ value = preg_quote ($ value); $ tag_regex = "/<(".$tag.")[^>] * $ attr \ s * = \ s * "." (["\"]) $ value \\ 2 [^>] *> (. *?)<\/\\1>/ "preg_match_all ($ tag_regex, $ xml, $ matches, PREG_PATTERN_ORDER); return $ matches;)

Finding Hexadecimal Color Values

An excellent example of a regular expression that matches hexadecimal color values ​​in given strings. What is this for? Maybe you want to write a CSS compression service, or something similar.

$ string = "# 555555"; if (preg_match ("/ ^ # (? :(? :( 3)) (1,2)) $ / i", $ string)) (echo "example 6 successful.";)

Search exampletitle on a given page

This interesting PHP code example with regexp searches and returns text between tags. and.

Feof ($ fp)) ($ page. = Fgets ($ fp, 4096);) $ titre = eregi (" (.*)", $ page, $ regs); echo $ regs; fclose ($ fp);

Parsing the Apache log

Most of the sites run on well-known Apache servers. If your site also runs on it, then you can parse the server log using php regexp.

// Logs: Apache web server // Successful hits to HTML files only. Useful for counting the number of page views. "^ ((? # client IP or domain name) S +) s + ((? # basic authentication) S + s + S +) s + [((? # date and time) [^]] +)] s +" (?: GET | POST | HEAD) ((? #File) / [^? "] + ?. html?) ?? ((? # Parameters) [^?"] +)? HTTP / + "s + (? # Status code) 200s + ((? # Bytes transferred) [- 0-9] +) s +" ((? # Referrer) [^ "] *)" s + "((? # User agent ) [^ "] *)" $ "// Logs: Apache web server // 404 errors only" ^ ((? # Client IP or domain name) S +) s + ((? # Basic authentication) S + s + S +) s + [((? # date and time) [^]] +)] s + "(?: GET | POST | HEAD) ((? #file) [^?"] +) ?? ((? # parameters) [ ^? "] +)? HTTP / + "s + (? # Status code) 404s + ((? # Bytes transferred) [- 0-9] +) s +" ((? # Referrer) [^ "] *)" s + "((? # User agent ) [^ "] *)" $ "

Example for checking password complexity

A great example of a regular expression that checks the difficulty level of a password. The password must be 6 characters long and contain at least one uppercase character, one lowercase character, and a number.

"A (? = [-_ a-zA-Z0-9] *?) (? = [-_ a-zA-Z0-9] *?) (? = [-_ a-zA-Z0-9] *?) [-_a-zA-Z0-9] (6,) z "

Replacing text emoticons with graphic emoticons

This code example will change the text smiley to your graphic one. An interesting and useful php snippet.

$ texte = "A text with a smiley :-)"; echo str_replace (":-)", " ", $ texte);

An example of a regular expression to get images fromhtml code

It is worth saying that this php code is used in wordpress to search and process images.

post_content; $ szSearchPattern = "~ ] * /> ~ "; // Run preg_match_all to grab all the images and save the results in $ aPics preg_match_all ($ szSearchPattern, $ szPostContent, $ aPics); // Check to see if we have at least 1 image $ iNumberOfPics = count ($ aPics); if ($ iNumberOfPics> 0) (// You can process your images here // In this example, they will just be displayed on the monitor for ($ i = 0; $ i< $iNumberOfPics ; $i++) { echo $aPics[$i]; }; }; endwhile; endif; ?>

Hope you found this collection of php regexp examples helpful. If there are interesting additions or examples of regular expressions (php), write in the comments.

mixed preg_replace(mixed pattern, mixed replacement, mixed subject [, int limit])

Searches subject for pattern matches and replaces them with replacement. If the limit parameter is specified, then the limit occurrences of the template will be replaced; if limit is omitted or equal to -1, all occurrences of the pattern will be replaced.

Replacement can contain references of the form \\ n or (since PHP 4.0.4) $ n, with the latter being preferred. Each such reference will be replaced with a substring corresponding to the n "n" subpattern enclosed in parentheses. N can take values ​​from 0 to 99, and the reference \\ 0 (or $ 0) matches the entire pattern. Subpatterns are numbered from left to right, starting from one ...

When using wildcard substitution using subpattern references, it may be possible for a number to immediately follow the mask. In this case, the \\ n notation results in an error: a reference to the first subpattern followed by the number 1 will be written as \\ 11, which will be interpreted as a reference to the eleventh subpattern. This confusion can be cleared up by using the \ $ (1) 1 construct, which points to an isolated reference to the first subpattern followed by the digit 1.

The output of this example will be:

April1,2003

If a pattern match is found during the execution of the function, the modified subject value will be returned, otherwise the original subject will be returned.

The first three parameters of the function preg_replace () can be one-dimensional arrays. If the array uses keys, when processing the array, they will be taken in the order in which they are located in the array. Array keys for pattern and replacement are optional. If you nevertheless decide to use indexes, to match patterns and strings involved in the replacement, use the function ksort () for each of the arrays.


Example 2. Using arrays with numeric indices as function arguments preg_replace ()

$ string = "The quick brown fox jumped over the lazy dog."; $ patterns [0] = "/ quick /";
$ patterns [1] = "/ brown /";
$ patterns [2] = "/ fox /"; $ replacements [2] = "bear";
$ replacements [1] = "black";
$ replacements [0] = "slow"; preg_replace ($ patterns, $ replacements, $ string);
?>

Result:

Result:

The slow black bear jumped over the lazy dog.

If the subject parameter is an array, wildcard search and replacement are performed for each of its elements. The returned result will also be an array.

In case the parameters pattern and replacement are arrays, preg_replace () alternately retrieves a pair of elements from both arrays and uses them for the search and replace operation. If the replacement array contains more elements than pattern, empty strings will be taken instead of the missing elements for replacement. If pattern is an array, and replacement is a string, each element of the pattern array will be searched for and replaced with pattern (the pattern will alternately be all the elements of the array, while the replacement string remains fixed). The variant when pattern is a string and replacement is an array does not make sense.

The / e modifier changes the behavior of a function preg_replace () in such a way that the replacement parameter, after performing the necessary substitutions, is interpreted as PHP code and only then is it used for replacement. When using this modifier, be careful: the replacement parameter must contain the correct PHP code, otherwise, in the line containing the function call preg_replace (), a syntax error occurs.


Example 3. Replacement by several templates

$ patterns = array ( "/ (19 | 20) (\ d (2)) - (\ d (1,2)) - (\ d (1,2)) /",
"/ ^ \ s * ((\ w +)) \ s * = /");
$ replace = array ("\\ 3 / \\ 4 / \\ 1 \\ 2", "$ \\ 1 =");
echo preg_replace ($ patterns, $ replace, "(startDate) = 1999-5-27");
?>

This example will output:

Converts all HTML tags to uppercase


Example 5. HTML to text converter

// $ document in the output should contain an HTML document.
// It is necessary to remove all HTML tags, javascript sections,
// whitespace characters. It is also necessary to replace some
// HTML entities to their equivalent.
$ search = array ( ""]*?>.*?"si", // Cut out javaScript
""<[\/\!]*?[^<>] *?> "si", // Strips out HTML tags
"" ([\ r \ n]) [\ s] + "", // Strips out whitespace characters
"" & (quot | # 34); "i", // Replaces HTML entities
"" & (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"); // interpret as php code$ replace = array ("",
"" ,
"\\1" ,
"\"" ,
"&" ,
"<" ,
">" ,
" " ,
chr (161),
chr (162),
chr (163),
chr (169),
"chr (\\ 1)"); $ text = preg_replace ($ search, $ replace, $ document);
?>

I have long wanted to deal with regular expressions. Although "to figure it out" - it is loudly said. To master the great art and become the master of regular expressions, you need to constantly deal with them. It is not enough to learn the syntax, special characters and modifiers - you need to know how to use them. And the ability to use comes with experience.

In this post I will lay out examples of using regular expressions, which I figured out myself.

Special characters table

Special character Description
\ Escaping character. Example: '/ Seo \ / smo /'- matches a line that has seo / smo in it.
^ Data start character. Example: '/ ^ Seo /'- matches a line that begins with the word seo.
$ End of data character. Example: '/ Blog $ /'- matches a line that ends with the word blog.
. Any character other than line feed. Example: '/Seo.ult/'- matches the string seopult, seo9ult, [email protected] etc.
Inside these brackets are listed characters, any of which can appear in this place, but only one. Example: ‘/ Seoult /’- only lines containing seopult, seokult or seomult will be matched.
| Or. See example below.
() Submask.
? One or zero occurrences of the preceding character or subpattern.
* Any number of occurrences of the preceding character or subpattern. Including zero.
+ One or more entries.
Example: '/Se+(op|om)?.*t/ ’- the letter s, then one or more letters e, after that the combination op or om can occur once, or maybe never, then any number of any symbols and the letter t.
(a, b) The number of occurrences of the preceding character or subpattern, a through b. Example: (0,) is the same as *, (0,1) is the same as ?, (3,5) is 3, 4, or 5 repetitions.

Simple examples of php scripts using regular expressions:

1) Previous and next expressions.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 // find a word with ing after Box. If the word is found, the function will return true, if not - false.$ pattern1 = "/ Box (? = ing) /"; preg_match ($ pattern1, "Box Day"); // false preg_match ($ pattern1, "Boxing Day"); // true // find a word without ing after box. If the word is found, the function will return true, if not - false.$ pattern2 = "/ box (?! ing) /"; preg_match ($ pattern2, "Box for iPhone and iPad"); // true preg_match ($ pattern2, "What is boxing day?"); // false preg_match ($ pattern2, "css-moz-box-shadow"); // true // find a word that doesn't come before ing box. If the word is found, the function will return true, if not - false.$ pattern3 = "/ (?

[^<]+?~ "," seo blog ", $ text); echo $ text;?>

3) Get and display the Alexa Rank of a given site.

1 2 3 4 5 6 7 8 9 "#
(.*?)
#si ", file_get_contents ( "http://www.alexa.com/siteinfo/($url)"), $ a); return trim (str_replace (",", "", strip_tags ($ a [1]))); ) $ alexa = alexa ($ url); echo $ alexa; ?>

(.*?)

#si ", file_get_contents (" http://www.alexa.com/siteinfo/($url) "), $ a); return trim (str_replace (", "," ", strip_tags ($ a))); ) $ alexa = alexa ($ url); echo $ alexa;?>

4) Get and display the title of the page.

1 2 3 4 5 (.*)<\/title>/ s ", $ str, $ m); echo $ m [1];?>

(.*)<\/title>/ s ", $ str, $ m); echo $ m;?>

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 \ n \ r \ t] / ", "", $ content); // replace line feed and tab characters with a space$ content = preg_replace ("/ (2,) /", "", $ content); // replace more than 2 spaces with one preg_match_all ("/ ] * href = (?: "| \" )(.*)(?:"|\" )[^<>]*>(.*)<\/a>/ iU ", $ content, $ links); // collect links if (sizeof ($ links [1])> 0) // if links are found($ out = array (); // array of external links foreach ($ links [1] as $ v) (if (preg_match ("/http:\/\/(www\.)(0,1)". $ domain. "/ i", $ v)) // filter out internal links(continue;) if (preg_match ( "/(http:|https:)?\/\/(www\.)(0,1)(.*)/i", $ v)) // external reference($ out = $ v;)) return $ out; ) return array (); ) $ domain = "site"; $ content = file_get_contents ("http: // site /"); $ getoutlinks = getoutlinks ($ content, $ domain); for ($ i = 0; $ i<= count ($getoutlinks ) ; $i ++ ) { echo $getoutlinks [ $i ] . "
" ; } ?>

] * href = (?: "| \") (. *) (?: "| \") [^<>]*>(.*)<\/a>/ iU ", $ content, $ links); // collect links if (sizeof ($ links)> 0) // if links are found ($ out = array (); // array of external links foreach ($ links as $ v ) (if (preg_match ("/ http: \ / \ / (www \.) (0,1)". $ domain. "/ i", $ v)) // filter out internal links (continue;) if (preg_match ("/(http:|https:)?\/\/(www\.)(0,1)(..com/"); $ getoutlinks = getoutlinks ($ content, $ domain); for ($ i = 0; $ i<= count($getoutlinks); $i++) { echo $getoutlinks[$i]."
"; } ?>

where:
preg_replace- performs search and replace by regular expression.
preg_match- Checks against a regular expression.
preg_match_all- finds all matches, while preg_match only finds the first one.
file_get_contents- get the contents of the file as one line.
trim- removes spaces at the beginning and end of a line.
str_replace- replaces the search string with a replacement string.
strip_tags- removes html and php tags from the string.
sizeof- gets the number of elements in a variable.
count- counts the number of elements in an array or the number of properties of an object.

int preg_match_all(string pattern, string subject, array & matches [, int flags [, int offset]])

Searches subject for all matches of pattern and places the result in matches in the order specified by the combination of flags.

After finding the first match, subsequent searches will be carried out not from the beginning of the string, but from the end of the last found occurrence.

The optional flags parameter can combine the following values ​​(you must understand that using PREG_PATTERN_ORDER at the same time with PREG_SET_ORDER meaningless):

PREG_PATTERN_ORDER

If this flag is set, the result is ordered as follows: $ matches contains an array of full matches of the pattern, $ matches contains an array of occurrences of the first subpattern, and so on.

Returns the number of occurrences of the pattern found (can be zero), or FALSE if any errors occurred during execution.


Example 2. Greedy Matching HTML Tags

// The \\ 2 entry is an example of using subpattern references.
// It means that the substring must match the string captured
// the second subpattern, in our example it is ([\ w] +).
// Extra slash is required as double quotes are used.
$ html = "bold textclick me" ; preg_match_all ( "/(<([\w]+)[^>]*>)(.*)(<\/\\2>)/" , $ html, $ matches); $ i = 0; $ i< count ($matches [ 0 ]); $i ++) {
echo "matched:". $ matches [0] [$ i]. "\ n";
echo "part 1:". $ matches [1] [$ i]. "\ n";
echo "part 2:". $ matches [3] [$ i]. "\ n";
echo "part 3:". $ matches [4] [$ i]. "\ n \ n";
}
?>

The result of the example:







2022 gtavrl.ru.