PHP/String/preg match

Материал из Web эксперт
Перейти к: навигация, поиск

Содержание

Capturing with nested parentheses

   <source lang="html4strict">

<? if (preg_match("/^(\d{5})(-(\d{4}))?$/",$_POST["zip"],$matches)) {

   print "The beginning of the ZIP Code is: $matches[1]\n";
   if (isset($matches[2])) {
       print "The ZIP+4 is: $matches[3]";
   }

} ?>

 </source>
   
  


Capturing with preg_match()

   <source lang="html4strict">

<? if (preg_match("/^(\d{5})(-\d{4})?$/",$_POST["zip"],$matches)) {

   print "$matches[0] is a valid US ZIP Code\n";
   print "$matches[1] is the five-digit part of the ZIP Code\n";
   if (isset($matches[2])) {
       print "The ZIP+4 is $matches[2];";
   } else {
       print "There is no ZIP+4";
   }

} $is_bold = preg_match("@([^<]+)@",$html,$matches); if ($is_bold) {

   print "The bold text is: $matches[1]";

} ?>

 </source>
   
  


Checking the syntax of an e-mail address

   <source lang="html4strict">

if (! preg_match("/^[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}$/i", $_POST["email"])) {

   $errors[] = "Please enter a valid e-mail address";

}

 </source>
   
  


Check quotes in a file

   <source lang="html4strict">

<?php

 $file = fopen("data.txt", "r") or die("Cannot open file!\n");
 $lineNbr = 0;
 while ($line = fgets($file, 1024)) {
   $lineNbr++;
   if (preg_match("/^[^\"]*\"([^\"]*|([^\"]*\"[^\"]*\"[^\"]*)*)$/", $line)) {
     echo "Found match at line " . $lineNbr . ":  " . $line;
   }
 }
 fclose($file);

?>

 </source>
   
  


Combine patterns with the pipe (|) character to create branches

   <source lang="html4strict">

<? $test = "www.example.ru"; if ( preg_match( "/www\.example(\.ru|\.co\.uk)/", $test, $array ) ) {

 print "it is a $array[1] domain
";

} ?>

 </source>
   
  


Detecting ZIP Codes in Strings

   <source lang="html4strict">

<?php function detect_zipcode($string) {

   return preg_match("/\b\d{5}(-\d{4})?\b/", $string);

}

echo "
";
if (detect_zipcode("MD  11101-3883")) {
    echo "Test 1: true\n";
}
if (detect_zipcode("The zipcode 26623 is the area in which I grew up.")) {
    echo "Test 2: true\n";
}
if (detect_zipcode("The Phone Number is 301-555-1212")) {
    echo "Test 3: true\n";
}
if (detect_zipcode("426969-313109")) {
    echo "Test 4: true\n";
}
echo "
";

?>

 </source>
   
  


Efficiently finding lines that match a pattern

   <source lang="html4strict">

<? $fh = fopen("/path/to/your/file.txt", "r") or die($php_errormsg); while (!feof($fh)) {

   $line = fgets($fh);
   if (preg_match($pattern, $line)) { $ora_books[ ] = $line; }

} fclose($fh); ?>

 </source>
   
  


Finding All Matching Lines in a File

   <source lang="html4strict">

<?php $file = fopen("testfile.txt", "r") or die("Cannot open file!\n"); while ($line = fgets($file, 1024)) {

   if (preg_match("/Hello( World!)?/", $line)) { 
       echo "Found match: " . $line; 
   } else { 
       echo "No match: " . $line; 
   } 

} fclose($file); ?>

 </source>
   
  


Finding Lines with an Odd Number of Quotes

   <source lang="html4strict">

<?php $file = fopen("data.txt", "r") or die("Cannot open file!\n"); $lineNbr = 0; while ($line = fgets($file, 1024)) {

   $lineNbr++; 
   if (preg_match("/^[^\"]*\"([^\"]*|([^\"]*\"[^\"]*\"[^\"]*)*)$/", $line)) { 
       echo "Found match at line " . $lineNbr . ": " . $line; 
   } 

} fclose($file); ?>

 </source>
   
  


Finding Repeated Words

   <source lang="html4strict">

<?php function showMatchResults($str) {

   if (preg_match("/\b(\w+)\s+\\1\b/i", $str)) { 
       echo "Match successful: "" . $str . ""\n"; 
   } else { 
       echo "Match failed: "" . $str . ""\n"; 
   } 

} showMatchResults("Hello World!"); ?>

 </source>
   
  


Finding the nth Occurrence of a Match

   <source lang="html4strict">

<?php preg_match("/\d/", "1 and 2 and 3 and 4", $matches); echo "Value: " . $matches[0][2] . "\n"; ?>

 </source>
   
  


Finding Words Not Followed by Other Words

   <source lang="html4strict">

<?php

 $regex = "/\bhello\b(?!\sworld\b)/";
 $valid = "hello";
 $invalid = "hello world!";
 if (preg_match($regex, $valid)) {
   echo "Found match:  "" . $valid . ""\n";
 } else {
   echo "No match:  "" . $valid . ""\n";
 }
 if (preg_match($regex, $invalid)) {
   echo "Found match:  "" . $invalid . ""\n";
 } else {
   echo "No match:  "" . $invalid . ""\n";
 }

?>

 </source>
   
  


Find the first "p" string and match as many characters as possible until the last possible "t" is reached.

   <source lang="html4strict">

<? $text = "pot post pat patent"; if (preg_match ( "/p.*t/", $text, $array ) ) {

print "
\n";
  print_r( $array );
  print "
\n";

} ?>

 </source>
   
  


Get the start and end of the string when m is enabled, you should use \A and \z, like this:

   <source lang="html4strict">

preg_match("/\AThis/m", $multitest);

   // returns true if the string starts with "This" (true)
   preg_match("/symbol\z/m", $multitest);
   // returns true if the string ends with "symbol" (false)
 
 </source>
   
  


i renders the regular expression non case sensitive

   <source lang="html4strict">

<?php

   $s = "Another beautiful day";
   echo (preg_match ("/BEautiFul/i", $s) ? "MATCH" : "NO MATCH") . "\n";

?>

 </source>
   
  


Looking for any lowercase alphabetical character or the numbers 3, 4, and 7

   <source lang="html4strict">

<? if ( preg_match("/[a-z347]+/", "AB asdf123123asdfasdf", $array) ) {

print "
\n";
  print_r( $array );
  print "
\n";

} ?>

 </source>
   
  


Matching Patterns with preg_match()

   <source lang="html4strict">

preg_match() accepts four arguments:

   a regular expression string, 
   a source string, 
   an array variable (which stores matches), 
   and an optional fourth flag argument. 
   

preg_match() returns 0 if a match is found and 1 otherwise. These numbers represent the number of matches the function can make in a string.

<?

print "
\n";
print preg_match("/is/", "this is a test", $array) . "\n";
print_r( $array );
print "
\n";

?>

 </source>
   
  


Matching with preg_match()

   <source lang="html4strict">

<? if (preg_match("/^\d{5}(-\d{4})?$/",$_POST["zip"])) {

   print $_POST["zip"] . " is a valid US ZIP Code";

} $is_bold = preg_match("@[^<]+@",$html); ?>

 </source>
   
  


Negate the characters in the character class

   <source lang="html4strict">

<? if ( preg_match("/[^a-z347]+/","AB asdf123123asdf", $array) ) {

print "
\n";
  print_r( $array );
  print "
\n";

} ?>

 </source>
   
  


Parsing a date with a regular expression

   <source lang="html4strict">

<?php $date = "2010-12-03 05:12:56"; preg_match("/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/",$date,$date_parts); ?>

 </source>
   
  


preg_match

   <source lang="html4strict">

<?php

  $line = "this is a test!"; 
  if (preg_match("/\bis\b/i", $line, $match)) print "Match found!";

?>

 </source>
   
  


preg_match( ) calls and what they match

   <source lang="html4strict">

<?

   if (preg_match("/php/i", "PHP")) {
           print "Got match!\n";
   }

?>

 </source>
   
  


preg_match() function returns true if pattern exists, and false otherwise.

   <source lang="html4strict">

Its syntax follows: int preg_match (string pattern, string string [, array pattern_array]) <?

   $line = "virtual";
   if (preg_match("/\bVi\b/i", $line, $match)) :
        print "Match found!";
   endif;

?>

 </source>
   
  


PREG_OFFSET_CAPTURE and preg_match()

   <source lang="html4strict">

<?php

   $s = "It is a beautiful day";
   preg_match ("/beautiful/", $s, $matches, PREG_OFFSET_CAPTURE);
   var_dump ($matches);

?>

 </source>
   
  


Put the word boundary character to the test

   <source lang="html4strict">

<? $text = "pot post pat patent"; if ( preg_match( "/\bp\w+t\b/", $text, $array ) ) {

print "
\n";
  print_r( $array );
  print "
\n";

} ?>

 </source>
   
  


Regular expressions using +, *, and ?

   <source lang="html4strict">

Regexp Result

preg_match("/[A-Z]+/", "123") False

preg_match("/[A-Z][A-Z0-9]+/i", "A123") True

preg_match("/[0-9]?[A-Z]+/", "10GreenBottles") True; matches "0G"

preg_match("/[0-9]?[A-Z0-9]*/i", "10GreenBottles") True

preg_match("/[A-Z]?[A-Z]?[A-Z]*/", "") True; zero or one match, then zero or one match, then zero or more means that an empty string matches

 </source>
   
  


Regular expressions using braces

   <source lang="html4strict">

Regexp Result

preg_match("/[A-Z]{3}/", "FuZ") False; the regexp will match precisely three uppercase letters

preg_match("/[A-Z]{3}/i", "FuZ") True; same as above, but case-insensitive this time

preg_match("/[0-9]{3}-[0-9]{4}/", "555-1234") True; precisely three numbers, a dash, then precisely four. This will match local U.S. telephone numbers, for example

preg_match("/[a-z]+[0-9]?[a-z]{1}/", "aaa1") True; must end with one lowercase letter

preg_match("/[A-Z]{1,}99/", "99") False; must start with at least one uppercase letter

preg_match("/[A-Z]{1,5}99/", "FINGERS99") True; "S99", "RS99", "ERS99", "GERS99", and "NGERS99" all fit the criteria

preg_match("/[A-Z]{1,5}[0-9]{2}/i", "adams42") True

 </source>
   
  


s modifier: use . to match characters across multiple lines.

   <source lang="html4strict">

//access the first and last words of a string

<? $text = "start with this line\nand you will reach\na conclusion in the end\n"; if ( preg_match( "/^(\w+).*?(\w+)$/", $text, $array ) ) {

print "
\n";
  print_r( $array );
  print "
\n";

} ?>

 </source>
   
  


Testing the Complexity of Passwords

   <source lang="html4strict">

<?php

 $values = array(
   "password",    // Bad
   "P4ssw0rd",    // Good
   );
 foreach ($values as $value) {
   if (! preg_match( "/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{8,16}/", $value)) {
     printf("Bad password:  "%s"\n", $value);
   } else { 
     printf("Good password:  "%s"!\n", $value);
   }
 }

?>

 </source>
   
  


Use regular expression to check each line of the code

   <source lang="html4strict">

<?php

 $file = fopen("data.txt", "r") or die("Cannot open file!\n");
 while ($line = fgets($file, 1024)) {
   if (preg_match("/Hello( World!)?/", $line)) {
     echo "Found match:  " . $line;
   } else {
     echo "No match: " . $line;
   }
 }
 fclose($file);

?>

 </source>
   
  


Using preg_match to return an array of matches that start with ple

   <source lang="html4strict">

<?php $subject = "example"; $pattern = "/^ple/"; preg_match($pattern, $subject, $matches); print_r($matches); ?>

 </source>
   
  


Validating numbers with regular expressions

   <source lang="html4strict">

<?php if (! preg_match("/^-?\d+$/"$_POST["rating"])) {

   print "Your rating must be an integer.";

} if (! preg_match("/^-?\d*\.?\d+$/",$_POST["temperature"])) {

  print "Your temperature must be a number.";

} ?>

 </source>
   
  


Words and Whitespace Regexps

   <source lang="html4strict">

$string = "Foolish child!";

   preg_match("/[\S]{7}[\s]{1}[\S]{6}/", $string);
 
 </source>