60 likes | 311 Views
PHP – Pattern matching, search and replacement. The PCRE library is a set of functions that implement regular expression pattern matching using the same syntax and semantics as Perl 5 There are a few differences preg_grep, preg_match, preg_replace. PHP – search and replacement. preg_replace
E N D
PHP – Pattern matching, search and replacement • The PCRE library is a set of functions that implement regular expression pattern matching using the same syntax and semantics as Perl 5 • There are a few differences • preg_grep, preg_match, preg_replace
PHP – search and replacement • preg_replace • Perform a regular expression search and replace • preg_replace( pattern, replacement, subject [, int limit] ) • Searches subject for matches to pattern (a regular expression) and replaces them with replacement
PHP – search and replacement • preg_replace( pattern, replacement, subject [, int limit] ) • Limit is optional • If not specified or –1 all matches are replaced (global) • If specified the first limit matches will be replaced
PHP – search and replacement • $colors = "red blue yellow red red green"; • $result = preg_replace( "/red/", "purple", $colors, 2 ); • echo “$result"; • purple blue yellow purple red green
PHP – regular expression • There are modifiers: i, e, s, m, .. • There are meta-characters: ?, *, +, \w, \d, .. • Remember the pattern matched: use ( ) back reference with $1, $2, .. • explore at www.php.net (search for preg_replace)