Searching within strings is one thing; replacing all occurrences with something else is completely different. Using regular expressions, this is relatively easy; you just have to know the respective function names:
Replacing Matches Using POSIX (ereg_replace.php) and PCRE (preg_replace.php)POSIX: <?php $string = '02/01/06'; echo ereg_replace( '([0-9][0-9]?)/([0-9][0-9]?)/([0-9][0-9]?)', '\\2/\\1/\\3', $string ); ?> PCRE: <?php $string = '02/01/06'; echo preg_replace( '#(\d{1,2})/(\d{1,2})/(\d{1,2})#', '$2/$1/$3', $string ); ?> Within the regular expression for the replace term, you can use references to subpatterns. The complete match is referred to by \0 in POSIX and $0 in PCRE. Then count parentheses from inside to outside, from left to right: The contents of the first parentheses are referenced by \1 or $1, the second parentheses are accessed using \2 or $2, and so on. With this in mind, the replacement can be done. In the example, a U.S. date (month/day/year) is converted to a U.K. date (day/month/year).
If you have a static pattern, without any quantifiers or special characters, using str_replace() is almost always faster. The parameter order for this is: first the string(s) to search for; then the replacement(s); and, finally, the string where the search and replace shall take place. You can provide strings or arrays of strings in the first two parameters. The following code removes all punctuation from the text. Replacing Without Regular Expressions (str_replace.php)<?php $string = 'To be, or not to be; that\'s the question?!'; echo str_replace( array('.', ',', ':', ';', '!', '?'), '', $string ); ?> |