【问题标题】:Keep Only subdirectory from href and src (ROOT html links )只保留 href 和 src 的子目录(ROOT html 链接)
【发布时间】:2022-11-03 00:18:52
【问题描述】:

您好,我有从外部 url 复制 html 并在我的页面上回显的代码。 一些 HTML 内部有链接和/或图片 SRC。 我需要一些帮助来截断它们(从绝对 url 到 $data 内的相对 url)

例如:在html里面有href

<a href="https://www.trade-ideas.com/products/score-vs-ibd/" >

or SRC

<img src="http://static.trade-ideas.com/Filters/MinDUp1.gif">

我想只保留子目录。

/products/score-vs-ibd/z

/Filters/MinDUp1.gif

也许使用 preg_replace ,但我不熟悉正则表达式。

这是我的原始代码,效果很好,但现在我卡住了截断链接。

<?php
$post_tags = get_the_tags();
if ( $post_tags ) {
$tag = $post_tags[0]->name; 
}   
$html= file_get_contents('https://www.trade-ideas.com/ticky/ticky.html?symbol='. "$tag");

$start = strpos($html,'<div class="span3 height-325"');
$end =  strpos($html,'<!-- /span -->',$start);
$data= substr($html,$start,$end-$start);
echo $data ;
?>

【问题讨论】:

    标签: php wordpress url truncate


    【解决方案1】:

    这是代码:

    function getUrlPath($url) {
       $re = '/(?:https?://)?(?:[^?/s]+[?/])(.*)/';
       preg_match($re, $url, $matches);
       return $matches[1];
    }
    

    示例:getUrlPaths("http://myassets.com:80/files/images/image.gif") 返回文件/图像/image.gif

    【讨论】:

      【解决方案2】:

      您可以使用preg_match_all() 使用正则表达式找到 html 字符串中的所有 URL。
      正则表达式:

      '/=['"](https?://.*?(/.*))['"]/i'
      

      将为每次出现="http://domain/path"='https://domain/path?query'(http/https,单引号或双引号,带/不带查询字符串)捕获整个 URL 和路径/查询字符串。
      然后你可以使用str_replace() 来更新 html 字符串。

      <?php
      $html = '<a href="https://www.trade-ideas.com/products/score-vs-ibd/" >
      <img src="http://static.trade-ideas.com/Filters/MinDUp1.gif">
      <img src='https://static.trade-ideas.com/Filters/MinDUp1.gif?param=value'>';
      
      $pattern = '/=['"](https?://.*?(/.*))['"]/i';
      $urls = [];
      preg_match_all($pattern, $html, $urls);
      //var_dump($urls);
      foreach($urls[1] as $i => $uri){
          $html = str_replace($uri, $urls[2][$i], $html);
      }
      echo $html;
      

      Run it live here.

      笔记,这将更改紧跟在= 之后的所有用引号括起来的绝对 URL。

      【讨论】:

        猜你喜欢
        • 2021-08-17
        • 1970-01-01
        • 1970-01-01
        • 2023-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-04
        • 2019-06-30
        相关资源
        最近更新 更多