删除特定字符后的字符串部分

时间:2020-01-31 21:08:36

标签: php html css

我有一个问题: 我在PHP程序中的Google搜索中使用了file_get_contents(),但是每当我单击链接时,它都会带我到一个名为/ url的页面?服务器上的网址中有一个随机的字母和数字字符串。我想做的是使用可能的php删除此标记中url中的所有内容,而不删除此代码段中url的&amp部分之后的所有内容:

<a href="/url?q=https://www.dictionary.com/browse/something&amp;sa=U&amp;ved=2ahUKEwjrxPm33a7nAhWSZ80KHfVUC_sQFjAKegQICRAB&amp;usg=AOvVaw3d2t7GukCiuBVOJOqc29Us"><div class="BNeawe vvjwJb AP7Wnd">Something | Definition of Something at Dictionary.com</div><div class="BNeawe UPmit AP7Wnd">https://www.dictionary.com › browse › something</div></a>

此刻我的完整源代码如下:

<style>
  .KP7LCb { display:none;}
  #extrares { display:none;}
  .bz1lBb { display:none;}
  .cOl4Id { display:none;}
</style>

<?php
  $google = file_get_contents("https://www.google.co.uk/search?q=google");
  $google1 = str_replace("/url?q=", "", $google);

  echo $google1;
?>

1 个答案:

答案 0 :(得分:0)

您基本上想按顺序执行三件事:

  1. 解析HTML。
  2. 解析网址。
  3. 解析查询字符串。

第一个任务的可能工具(尽管在这里可能被认为过高了)是DOM解析器,例如:

// Error checking omitted
$html = '<a href="/url?q=https://www.dictionary.com/browse/something&amp;sa=U&amp;ved=2ahUKEwjrxPm33a7nAhWSZ80KHfVUC_sQFjAKegQICRAB&amp;usg=AOvVaw3d2t7GukCiuBVOJOqc29Us"><div class="BNeawe vvjwJb AP7Wnd">Something | Definition of Something at Dictionary.com</div><div class="BNeawe UPmit AP7Wnd">https://www.dictionary.com › browse › something</div></a>';
$doc = new DOMDocument();
$doc->loadHTML($html);
$url = $doc->getElementsByTagName('a')[0]->getAttribute('href');

有了URL,就可以获取查询片段:

$query = parse_url($url, PHP_URL_QUERY);

...最后解析它:

parse_str($query, $get);
$link = $get['q'];