使用 preg_match 和 preg_replace
我有两个字符串,例如:
http://localhost/web/
和
http://localhost/web/category/
有时会变成:
http:// localhost/web/2/
、http://localhost/web/3/
等...
和
http://localhost/web/category/2/< /code>、
http://localhost/web/category/3/
等...
我想进行验证并且:
如果链接是 http://localhost/web/
它保持不变。
如果链接是 http://localhost/web/2/
则变为 http://localhost/web/
如果链接是 http://localhost /web/category/
它保持不变。
如果链接是 http://localhost/web/category/2/
它会变成 http://localhost/web/category/
我想应该使用 <代码>preg_replace()和preg_match()
。
我该怎么做呢?
谢谢。
I have two strings like:
http://localhost/web/
and
http://localhost/web/category/
which sometimes become:
http://localhost/web/2/
, http://localhost/web/3/
etc....
and
http://localhost/web/category/2/
, http://localhost/web/category/3/
etc...
I want to make a verification and:
If the link is http://localhost/web/
it remains the same.
If the link is http://localhost/web/2/
it becomes http://localhost/web/
If the link is http://localhost/web/category/
it remains the same.
If the link is http://localhost/web/category/2/
it becomes http://localhost/web/category/
I guess it should be done using preg_replace()
and preg_match()
.
How can I do it?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以下是您需要的正则表达式:
对于 preg_replace 函数,您将需要一个替换语句,该语句将根据您的条件重写字符串:
上面的替换语句本质上连接第一个捕获组(第一组括号,其计算值到 http://localhost/),第二个捕获组为“web”或“web/category”。由于我们不关心最后一个捕获组($3),因此我们不会将其添加到替换语句中;但是,我们可以,因为我们正在捕获它。如果你不想捕获它,请将这个“([\d]+)”替换为“[\d]+”。
以下是示例代码,它将模式与替换合并在一起,形成完整的 preg_replace 语句:
将上述代码放入文件中(例如:replace.php)并通过命令行运行它:
The following is the regular expression you will need:
For the preg_replace function, you will need a replacement statement which will re-write the string based on your criteria:
The above replacement statement essentially concatenates the first capture group (first set of parens which evaluates to http://localhost/) with the second capture group of either 'web' or 'web/category'. Since we don't care about the last capture group ($3), we don't add it to the replacement statement; however, we could since we are capturing it. If you don't want to capture it, replace this "([\d]+)" with "[\d]+".
The following is sample code which incorporates the pattern with the replacement to form a full preg_replace statement:
Toss the above code into a file (for example: replace.php) and run it via the command-line: