【问题标题】:Find all URLS in a string and encode query string?查找字符串中的所有 URL 并对查询字符串进行编码?
【发布时间】:2014-02-03 08:32:16
【问题描述】:

我想在一个字符串(卷曲结果)中查找所有 URL,然后对这些结果中的任何查询字符串进行编码,例如

找到的网址:

http://www.example.com/index.php?favoritecolor=blue&favoritefood=sharwarma

用编码字符串替换所有找到的 URL(我只能做其中一个)

http%3A%2F%2Fwww.example.com%2Findex.php%3Ffavoritecolor%3Dblue%26favoritefood%3Dsharwarma

但是在 html curl 响应中执行此操作,从 html 页面中查找所有 URL。 提前谢谢你,我已经搜索了几个小时。

【问题讨论】:

  • 使用preg_replace_callback() 对您在字符串中找到的每个网址调用urlencode
  • 为什么我们没有在您的问题中看到您的代码?
  • 你会在一个字符串中有超过 1 个 url.. PS-你能澄清一下你想要做什么
  • 谢谢大家,php 代码 (DOM) 运行良好。我现在怎么能说再次找到所有 URL(包括图像 src、css url 等),然后将 example.com/… 之类的内容更改/替换为 url.com/… 谢谢!

标签: php url curl replace encode


【解决方案1】:

如果您的 CURL 结果是 HTML 页面并且您只需要 a 链接(而不是图像或其他可点击元素),这将满足您的需求。

$xml = new DOMDocument();

// $html should be your CURL result
$xml->loadHTML($html);

// or you can do that directly by providing the requested page's URL to loadHTMLFile
// $xml->loadHTMLFile("http://...");

// this array will contain all links
$links = array();

// loop through all "a" elements
foreach ($xml->getElementsByTagName("a") as $link) {
    // URL-encodes the link's URL and adds it to the previous array
    $links[] = urlencode($link->getAttribute("href"));
}

// now do whatever you want with that array

$links 数组将包含页面中以 URL 编码格式找到的所有链接。

编辑:如果您想替换页面中的所有链接同时保留其他所有内容,最好使用DOMDocument 而不是正则表达式(相关:why you shouldn't use regex to handle HTML),这是我的代码的编辑版本,它替换了每个链接使用其 URL 编码等效项,然后将页面保存到变量中:

$xml = new DOMDocument();

// $html should be your CURL result
$xml->loadHTML($html);

// loop through all "a" elements
foreach ($xml->getElementsByTagName("a") as $link) {
    // gets original (non URL-encoded link)
    $original = $link->getAttribute("href");

    // sets new link to URL-encoded format
    $link->setAttribute("href", urlencode($original));
}

// save modified page to a variable
$page = $xml->saveHTML();

// now do whatever you want with that modified page, for example you can "echo" it
echo $page;

代码基于this

【讨论】:

  • 不要将 htmlDOM 用于跟踪 html。这个问题说'如何在文本not html 中找到网址'
  • @MahmoudEskandari find all URLs in a string (curl results)find all URLS from html page 明确表示 OP 希望使用 HTML 页面,在我看来这是最干净的方法。
  • 嗨,谢谢你们,但是当我在下面添加确切的 php 时,提供 $xxx 是我的 html 结果,我得到一个空白屏幕...
  • 谢谢你,这似乎工作......只需要做 yum install php-xml
  • 我现在怎么能说再次找到所有这些 URL(包括图像 src、css url 等),然后将 example.com/… 之类的内容更改/替换为 url.com/…
【解决方案2】:

不要直接使用php Dom,会拖慢你的执行时间,使用simplehtmldom,很简单

function decodes($data){
foreach($data->find('a') as $hres){
$bbs=$hres->href;
$hres->__set("href", urlencode($bbs));
}
return $data;
}

【讨论】:

    猜你喜欢
    • 2017-05-17
    • 2014-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-16
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多