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

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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化