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 chaquopy python 安卓
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题