duanjiao7440 2018-01-15 01:04
浏览 20

如何在URL上使用preg_replace

How do I use preg_replace text/url. For example, I have a url like this: http://www.web.org/dorama/1201102144/hitoya-no-toge. I just want to show web.org. The url is not always same, for example sometimes it's: http://www.web.org/movies/123/no etc.

I only know the basics of it. Here is what I tried. It still does not delete the slash.

$url = "http://www.web.org/dorama/1201102144/hitoya-no-toge";
$patterns = array();
$patterns[0] = '/http:/';
$patterns[1] = '/dorama/';
$patterns[2] = '/1201102144/';
$replacements = array();
$replacements[2] = '';
$replacements[1] = '';
$replacements[0] = '';
echo preg_replace($patterns, $replacements, $url);

result when i run it //www.web.org///hitoya-no-toge

  • 写回答

2条回答 默认 最新

  • drcomwc134525 2018-01-15 01:17
    关注

    Use preg_match instead preg_replace i think http://php.net/manual/en/function.preg-match.php

    // get host name from URL
    preg_match('@^(?:http://)?([^/]+)@i', $url, $matches);
    $host = $matches[1];
    
    // get last two segments of host name
    preg_match('/[^.]+\.[^.]+$/', $host, $matches);
    echo "{$matches[0]}"
    

    If use https change http to https, I don't know how to make it work for http and https.

    评论

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源