【问题标题】:preg_replace to modify urls coming from curlpreg_replace 修改来自 curl 的 url
【发布时间】:2014-08-23 00:31:06
【问题描述】:

我需要替换 curl 从另一个站点获取的页面中的 url。我的 php curl 代码是;

<?php

$ch = curl_init ("http://www.externalwebsite.com/index.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$page = curl_exec($ch);
preg_match('#<div class="headline"[^>]*>(.+?)</div>#is', $page, $matches);
foreach ($matches as &$match) {
    $match = $match;
}
$html=$matches[1];   
$html = preg_replace('~a href="([a-z,.\-]*)~si', '"', $html); //NEED TO CHANGE THIS                                         

    echo $html;

?>

此代码正常工作,直到 url 包含除 id 之外的任何数字字符。这是没有任何 preg_replace 命令的 html 的样子。

<div class="swiper-slide red-slide">
    <div class="title"><a href="http://www.externalwebsite.com/title-of-the-3-page-192345.htm" class="image">
<img src="http://www.externalwebsite.com/d/news/94406.jpg"/></a></div></div>

如果我使用上面的 preg_replace 命令 html 看起来像;

<div class="swiper-slide red-slide">
    <div class="title"><a href="http://www.mywebsite.com/read_curl.php?id=3-page-192345" class="image">
<img src="http://www.externalwebsite.com/d/news/94406.jpg"/></a></div></div>

但一定是这样的;

<div class="swiper-slide red-slide">
    <div class="title"><a href="http://www.mywebsite.com/read_curl.php?id=192345" class="image">
<img src="http://www.externalwebsite.com/d/news/94406.jpg"/></a></div></div>

只有 id 必须保留,所有其他内容必须删除。有人可以帮帮我吗?

更新:页面的标题是动态变化的,最后 6 位是 id,唯一的东西必须保留在 url 中。

【问题讨论】:

  • 您的最后两个代码看起来相同

标签: php url curl


【解决方案1】:

用户 PHP 正则表达式:

/\d{6}/

结果:

<?php
    $str='<div class="swiper-slide red-slide">
        <div class="title"><a href="http://www.externalwebsite.com/title-of-the-3-page-192345.htm" class="image">
    <img src="http://www.externalwebsite.com/d/news/94406.jpg"/></a></div></div>';
    preg_match("/\d{6}/", $str, $matches);
    $st = $matches[0];

    echo '<div class="swiper-slide red-slide">
        <div class="title"><a href="http://www.externalwebsite.com/read_curl?id='.$st.'" class="image">
    <img src="http://www.externalwebsite.com/d/news/94406.jpg"/></a></div></div>';

    ?>

【讨论】:

  • 谢谢,但是“title-of-the-3-page”会动态变化,我需要清除 id 之前的所有内容(最后 6 位数字)。
  • 你应该给出有问题的描述 - 无论如何等等
猜你喜欢
  • 1970-01-01
  • 2011-12-27
  • 2013-10-05
  • 2012-12-29
  • 2020-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多