Home > Backend Development > PHP Tutorial > PHP的preg_replace函数的问题

PHP的preg_replace函数的问题

WBOY
Release: 2016-06-23 13:52:01
Original
796 people have browsed it


$string = "april 15, 2003";$pattern = "/(/w+) (/d+), (/d+)/i";$replacement = "/${1}1,/$3";print preg_replace($pattern, $replacement, $string);/* output   ======april1,2003*/
Copy after login


$replacement = "/${1}1,/$3";
"/${1}1,/$3"这个是什么意思?


$patterns = array ("/(19|20)(/d{2})-(/d{1,2})-(/d{1,2})/",                   "/^/s*{(/w+)}/s*=/");$replace = array ("//3///4///1//2", "$//1 =");print preg_replace ($patterns, $replace, "{startdate} = 1999-5-27");
Copy after login


$replace = array ("//3///4///1//2", "$//1 =");这个也是什么意思?


回复讨论(解决方案)


${1} 就是匹配第一个 , $3就是匹配第三个。

${1} 就是匹配第一个 , $3就是匹配第三个。


第二段代码是错的,应该怎么改才能输出$startdate = 5/27/1999呢?

${1} 就是匹配第一个 , $3就是匹配第三个。


${1} 前面多一个转义\斜杠不是原文输出吗?

第一段代码是错误的,应写作

$string = "april 15, 2003";$pattern = "/(\w+) (\d+), (\d+)/i";$replacement = "\${1}1,\$3";print preg_replace($pattern, $replacement, $string);
Copy after login
Copy after login
$string = "april 15, 2003";$pattern = "/(\w+) (\d+), (\d+)/i";$replacement = '${1}1,$3';print preg_replace($pattern, $replacement, $string);
Copy after login
Copy after login


同理第二段代码应写作
$patterns = array ("/(19|20)(\d{2})-(\d{1,2})-(\d{1,2})/",                   "/^\s*{(\w+)}\s*=/");$replace = array ("\\3/\\4/\\1/\\2", "$\\1 =");print preg_replace ($patterns, $replace, "{startdate} = 1999-5-27");
Copy after login
Copy after login


$n 或 \\n 均是向后引用的记号,表示第 n 个圆括号中的内容

第一段代码是错误的,应写作

$string = "april 15, 2003";$pattern = "/(\w+) (\d+), (\d+)/i";$replacement = "\${1}1,\$3";print preg_replace($pattern, $replacement, $string);
Copy after login
Copy after login
$string = "april 15, 2003";$pattern = "/(\w+) (\d+), (\d+)/i";$replacement = '${1}1,$3';print preg_replace($pattern, $replacement, $string);
Copy after login
Copy after login


同理第二段代码应写作
$patterns = array ("/(19|20)(\d{2})-(\d{1,2})-(\d{1,2})/",                   "/^\s*{(\w+)}\s*=/");$replace = array ("\\3/\\4/\\1/\\2", "$\\1 =");print preg_replace ($patterns, $replace, "{startdate} = 1999-5-27");
Copy after login
Copy after login


$n 或 \\n 均是向后引用的记号,表示第 n 个圆括号中的内容


谢谢您,${1} 前面多一个转义斜杠\不是原文输出的意思吗?

双引号中 php 会试图将 $ 解释为变量的前导
字符串 "${1}" 将引起变量未定义的错误
所以要转义掉,这样才会把 ${1} 交给 prea_replace 去处理

双引号中 php 会试图将 $ 解释为变量的前导
字符串 "${1}" 将引起变量未定义的错误
所以要转义掉,这样才会把 ${1} 交给 prea_replace 去处理

谢谢您
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