Memory App
Programming
 




Match


echo preg_match("/cde/", "abcde", $matches); // 1

// $matches = [0] => cde
(1/5)

Delimiters

Any character can be used.

echo preg_match("/[a-z]/", "abcde"); // common delimiter

echo preg_match("&[a-z&]&", "abcde"); // escaped delimiter
(2/5)

Metacharacters

Every metacharacter represents a single character in the matched expression.

// Any character /./
echo preg_match("/./", "abc"); // 1
    // match any character
    // return TRUE

// Start /^/
echo preg_match("/^bc/", "abc"); // 0
    // match start of the string, then
    // match b, match c
    // return FALSE

// End /$/
echo preg_match("/c$/", "abc"); // 1
    // c, end of the string
(3/5)

Multiple matches

The preg_match_all() function allows you to perform multiple matches on a given string.

$matches = array();
if (preg_match_all("/([abc])d/", "a1bb b2cc c3dd", $matches)) {
    var_dump($matches);
}
/*
    array(2) {
      [0]=>
      array(3) {
        [0]=>
        string(2) "a1"
        [1]=>
        string(2) "b2"
        [2]=>
        string(2) "c3"
      }
      [1]=>
      array(3) {
        [0]=>
        string(1) "a"
        [1]=>
        string(1) "b"
        [2]=>
        string(1) "c"
      }
    }
*/
(4/5)

Replace matches

Using preg_replace(), you can replace text that matches a pattern we specify.

echo preg_replace("/a/", "x", "abc"); // xbc

echo preg_replace("/a{2}/", "x", "abaac"); // abxc
It is even possible to reuse captured subpatterns directly in the substitution string by prefixing their index with a dollar sign.

echo preg_replace("|[b](.*)[/b]|", "<b>$1</b>", "[b]abc[/b]"); // <b>abc</b>
We can also pass in an array of subjects on which to perform the search-and-replace operation. Regular expression (or expressions) are compiled once and reused multiple times.

$array = array("[b]abc[/b]", "[i]abc[/i]");

$result = preg_replace(
    array(
        "|[b](.*)[/b]|", 
        "|[i](.*)[/i]|",
    ), 
    array(
        "<b>$1</b>",
        "<i>$1</i>",
    ), 
    $array
);

print_r($array);
    // Array ( [0] => [b]abc[/b] [1] => [i]abc[/i] ) 

print_r($result);
    // Array ( [0] => <b>abc</b> [1] => <i>abc</i> )
Notice how the resulting array maintains the array structure that we passed in, which, however, is not passed by reference, nor is itmodified. http://php.net/manual/en/reference.pcre.pattern.modifiers.php

Questions



Top Reference > Programming
0/0 (80)  
Not Logged