doutizha7526 2015-05-05 11:11
浏览 33
已采纳

PHP - preg_replace删除斜杠和之后

Well, i want remove slash and rest of url after domain name. in this code:

$url = $_POST['url'];
$result = preg_replace('#/[^/]*$#', '', $url);
echo $result;

it will remove slash and after it (/index.php), but only when URL be something like this:

http://site.domain/index.php

but in this:

http://site.domain/index/test

or more slashes it will only remove last slash and trail (/test).

I want remove first slash after domain:

Example:

http://site.domain/index/test/test/test/test/test/test

Remove:

/index/test/test/test/test/test/test

Result:

http://site.domain

I don't know how to define first slash after domain and trails. Second problem is when url is:

http://test.domain

it will remove /test.com but i never want this, i want when url hasn't any slash after domain name it DO NOT remove second slash from http:// ! well, i know i should define that remove first slash after domain or in other hand first slash in path or php self.

  • 写回答

3条回答 默认 最新

  • douqulv6059 2015-05-05 11:13
    关注

    How about:

    $result = preg_replace('#((?:https?://)?[^/]*)(?:/.*)?$#', '$1', $url);
    

    This will kepp everything that is before the first slash (after http:// if present)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!