>我像这样从远程 url 获取源代码
$f = file_get_contents("http://www.example.com/abc/");
$str=htmlspecialchars( $f );
echo $str;
在该代码中,我想替换/提取任何类似
URL 的 URLhref="/m/offers/"
我想将该代码/链接替换为
href="www.example.com/m/offers/"
为此我用了
$newstr=str_replace('href="/m/offers/"','href="www/exmple.com/m/offers/',$str);
echo $newstr;
但这并没有取代任何东西,现在我想知道 1st ) 我可以在从远程 url 获取的代码中用 str_replace 替换吗,如果"是"如何......?如果"否"任何其他解决方案?
您的$str
中不会有任何"
,因为htmlspecialchars()
会在它到达您的str_replace
之前将它们全部转换为"
。
我开始假设所有 href 属性都属于标签。
因为我们知道所有标签是否都以相同的方式编写。 我将使用解释器来促进提取过程,而不是选择正则表达式
<?php
use Symfony'Component'DomCrawler'Crawler;
$base = "http://www.example.com"
$url = $base . "/abc/";
$html = file_get_contents($url);
$crawler = new Crawler($html);
$links = array();
$raw_links = array();
$offers = array();
foreach($crawler->filter('a') as $atag) {
$raw_links[] = $raw_link = $atag->attr('href');
$links[] = $link = str_replce($base, '', $raw_link);
if (strpos($link, 'm/offers') !== false) {
$offers[] = $link;
}
}
现在您拥有所有原始链接,相对链接和优惠链接
我使用 DomCrawler 组件