如何用正则表达式重新制作时区?
How to remake timezone with the regular expression?
在我的项目中,我通过 id 查找时区。
这是一个例子:
(GMT+07:00) Indian, Christmas
我怎样才能让它看起来像这样:
Indian\Christmas
用正则表达式?
您可以试试这个:1) 将 ()
之间的日期替换为空字符串 ""
,2) 将 ,
替换为 \
$string = '(GMT+07:00) Indian, Christmas';
$string = preg_replace("/\([^)]+\)/","",$string);// 'Indian, Christmas'
$string = preg_replace("/\, +\)/","\",$string);// 'Indian\Christmas'
一个 preg_replace()
调用就可以完成这项工作。我的模式和替换将匹配整个字符串并将其替换为将由 \
.
连接在一起的第一和第二捕获组
代码:(PHP Demo)
$input='(GMT+07:00) Indian, Christmas';
echo preg_replace('/\S+ ([^,]+), (.+)/','\$2','(GMT+07:00) Indian, Christmas');
// output: Indian\Christmas
这可以通过多种方式完成。如果您喜欢非正则表达式的方法,这里有一个利用每个字符串前面的静态长度的方法:
echo str_replace(', ','\',substr($input,12)); // same output
在我的项目中,我通过 id 查找时区。
这是一个例子:
(GMT+07:00) Indian, Christmas
我怎样才能让它看起来像这样:
Indian\Christmas
用正则表达式?
您可以试试这个:1) 将 ()
之间的日期替换为空字符串 ""
,2) 将 ,
替换为 \
$string = '(GMT+07:00) Indian, Christmas';
$string = preg_replace("/\([^)]+\)/","",$string);// 'Indian, Christmas'
$string = preg_replace("/\, +\)/","\",$string);// 'Indian\Christmas'
一个 preg_replace()
调用就可以完成这项工作。我的模式和替换将匹配整个字符串并将其替换为将由 \
.
代码:(PHP Demo)
$input='(GMT+07:00) Indian, Christmas';
echo preg_replace('/\S+ ([^,]+), (.+)/','\$2','(GMT+07:00) Indian, Christmas');
// output: Indian\Christmas
这可以通过多种方式完成。如果您喜欢非正则表达式的方法,这里有一个利用每个字符串前面的静态长度的方法:
echo str_replace(', ','\',substr($input,12)); // same output