PHP/String/preg match

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

Содержание

Capturing with nested parentheses

 
<?
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]";
    }
}
?>



Capturing with preg_match()

 
<?
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("@<b>([^<]+)</b>@",$html,$matches);
if ($is_bold) {
    print "The bold text is: $matches[1]";
}
?>



Checking the syntax of an e-mail address

 
if (! preg_match("/^[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}$/i", $_POST["email"])) {
    $errors[] = "Please enter a valid e-mail address";
}



Check quotes in a file

 
<?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);
?>



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

 
<?
$test = "www.example.ru";
if ( preg_match( "/www\.example(\.ru|\.co\.uk)/", $test, $array ) ) {
  print "it is a $array[1] domain<br/>";
}
?>



Detecting ZIP Codes in Strings

 
<?php
function detect_zipcode($string) {
    return preg_match("/\b\d{5}(-\d{4})?\b/", $string);
}
echo "<pre>";
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 "</pre>";
?>



Efficiently finding lines that match a pattern

 
<?
$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);
?>



Finding All Matching Lines in a File

 
<?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); 
?>



Finding Lines with an Odd Number of Quotes

 
<?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); 
?>



Finding Repeated Words

 
<?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!"); 
?>



Finding the nth Occurrence of a Match

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



Finding Words Not Followed by Other Words

 
<?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";
  }
?>



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

 
<?
$text = "pot post pat patent";
if (preg_match ( "/p.*t/", $text, $array ) ) {
  print "<pre>\n";
  print_r( $array );
  print "</pre>\n";
}
?>



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

 
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)



i renders the regular expression non case sensitive

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



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

 
<?
if ( preg_match("/[a-z347]+/", "AB asdf123123asdfasdf", $array) ) {
  print "<pre>\n";
  print_r( $array );
  print "</pre>\n";
}
?>



Matching Patterns with preg_match()

 
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 "<pre>\n";
print preg_match("/is/", "this is a test", $array) . "\n";
print_r( $array );
print "</pre>\n";
?>



Matching with preg_match()

 
<?
if (preg_match("/^\d{5}(-\d{4})?$/",$_POST["zip"])) {
    print $_POST["zip"] . " is a valid US ZIP Code";
}
$is_bold = preg_match("@<b>[^<]+</b>@",$html);
?>



Negate the characters in the character class

 
<?
if ( preg_match("/[^a-z347]+/","AB asdf123123asdf", $array) ) {
  print "<pre>\n";
  print_r( $array );
  print "</pre>\n";
}
?>



Parsing a date with a regular expression

 
<?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);
?>



preg_match

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



preg_match( ) calls and what they match

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



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

 
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;
?>



PREG_OFFSET_CAPTURE and preg_match()

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



Put the word boundary character to the test

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



Regular expressions using +, *, and ?

 
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



Regular expressions using braces

 
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



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

 
//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 "<pre>\n";
  print_r( $array );
  print "</pre>\n";
}
?>



Testing the Complexity of Passwords

 
<?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);
    }
  }
?>



Use regular expression to check each line of the code

 
<?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);
?>



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

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



Validating numbers with regular expressions

 
<?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.";
}
?>



Words and Whitespace Regexps

 
$string = "Foolish child!";
    preg_match("/[\S]{7}[\s]{1}[\S]{6}/", $string);