Home > Backend Development > PHP Tutorial > PHP about regular expressions_PHP tutorial

PHP about regular expressions_PHP tutorial

WBOY
Release: 2016-07-13 17:18:45
Original
851 people have browsed it

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

Copy after login


The above example will output:

kemo|addidas|就是这样的|haha|2013-12-14 11:40:43|tengx|buyao 
Copy after login

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);
?>
Copy after login

The above example will output:

kemo|addidas|就是这样的|haha|2013-12-14 12:07:55|weobo|lail
Copy after login







www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/621623.htmlTechArticleAt work, we often use regular expressions to match the data we want, and even The matched data is replaced with the data we need. All this seems difficult to do, but...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template