PHP中的未知修饰符"/"错误 [英] Unknown modifier '/' error in PHP
问题描述
preg_replace('/http:///ftp:///', 'https://', $value);
$value
中的
http://
和ftp://
应该替换为https://
http://
and ftp://
inside $value
should be replaced with https://
此代码给出错误:
preg_replace() [function.preg-replace]: Unknown modifier '/'
此任务的真正正则表达式是什么?
推荐答案
尝试使用其他定界符,例如#
:
Try using a different delimiter, say #
:
preg_replace('#http://|ftp://#', 'https://', $value);
或(不建议使用)对正则表达式中每次出现的定界符进行转义:
or (less recommended) escape every occurrence of the delimiter in the regex:
preg_replace('/http:\/\/|ftp:\/\//', 'https://', $value);
另外,您正在搜索模式http:///ftp://
,它实际上没有多大意义,也许是您想说的是http://|ftp://
.
Also you are searching for the pattern http:///ftp://
which really does not make much sense, may be you meant http://|ftp://
.
您可以将正则表达式缩短为:
You can make your regex shorter as:
preg_replace('#(?:http|ftp)#', 'https', $value);
了解错误: Unknown modifier '/'
在正则表达式'/http:///ftp:///'
中,第一个/
被视为起始定界符,而在:
之后的/
被视为结束定界符.现在我们知道可以为正则表达式提供修饰符以更改其默认行为.一些这样的修饰符是:
In your regex '/http:///ftp:///'
, the first /
is considered as starting delimiter and the /
after the :
is considered as the ending delimiter. Now we know we can provide modifier to the regex to alter its default behavior. Some such modifiers are:
-
i
:匹配大小写 不敏感 -
m
:多行搜索
i
: to make the matching case insensitivem
: multi-line searching
但是PHP在结束定界符之后看到的是另一个/
,并试图将其解释为修饰符,但失败了,从而导致错误.
But what PHP sees after the closing delimiter is another /
and tries to interpret it as a modifier but fails, resulting in the error.
preg_replace
返回更改后的字符串.
preg_replace
returns the altered string.
$value = 'http://foo.com';
$value = preg_replace('#http://|ftp://#', 'https://', $value);
// $value is now https://foo.com
这篇关于PHP中的未知修饰符"/"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!