At work, we often use regular expressions to match the data we want, and even replace the matched data with the data we need. All of this seems difficult to do, but if you are proficient in using regular expressions, these will not be a problem.
Example 1: $string is a string, define $patterns as an index-based array,
<?php date_default_timezone_set("Asia/Shanghai"); $string = 'kemo|addidas|就是这样的|haha|2013-12-13 09:00:09|weobo|lail'; $patterns = array(); $patterns[0] = '/2013-12-13 09:00:09/'; $patterns[1] = '/weobo/'; $patterns[2] = '/lail/'; $replacements = array(); $replacements[2] = date('Y-m-d H:i:s',time()); $replacements[1] = 'tengx'; $replacements[0] = 'buyao'; echo preg_replace($patterns, $replacements, $string); ?>
The above example will output:
kemo|addidas|就是这样的|haha|2013-12-14 11:40:43|tengx|buyao
In the above example, we can express the values we need to replace in the form of an index array, and then replace them one by one. Isn’t it very convenient?
Let’s look at another one. We need to convert the date in the string to the current date or something we need
Example 2:
<?php date_default_timezone_set("Asia/Shanghai"); $string = 'kemo|addidas|就是这样的|haha|2013-12-13 09:00:09|weobo|lail'; $pattern = '/\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}/'; $replacement = date('Y-m-d H:i:s',time()); echo preg_replace($pattern, $replacement, $string); ?>
kemo|addidas|就是这样的|haha|2013-12-14 12:07:55|weobo|lail