简体   繁体   English

如何从PHP DOM中的href =“ animals.html”获取链接?

[英]How do i get links from href=“animals.html” in php DOM?

My pages are www.example.com/somthing/types.html , www.example.com/somthing2/types.html this html files has a tag <a href="animals.html" . somthing,somthing2 我的页面是www.example.com/somthing/types.html,www.example.com/somthing2/types.html。此html文件具有标签<a href="animals.html" . somthing,somthing2 <a href="animals.html" . somthing,somthing2 are files every file contains links in types.html and files like animals.html in the same folders. <a href="animals.html" . somthing,somthing2是文件,每个文件都包含types.html中的链接和相同文件夹中的animals.html之类的文件。 when i get it with dom it shows only "animals.html" but i want to get "www.example.com/somthing/animals.html". 当我使用dom时,它仅显示“ animals.html”,但我想获取“ www.example.com/somthing/animals.html”。 how can i remove types.html from www.example.com/somthing/types.html and put www.example.com/somthing+/animals.html. 我如何从www.example.com/somthing/types.html中删除types.html并放入www.example.com/somthing+/animals.html。

i just need a way to remove "types.html" from www.example.com/somthing/types.html. 我只需要从www.example.com/somthing/types.html删除“ types.html”的方法。 keep the folder and remove the last part after this "/". 保留文件夹,并删除此“ /”后面的最后一部分。

i dont know always last part (file name) so i need a way to remove last thing after last "/". 我不知道总是最后一部分(文件名),所以我需要一种删除最后一个“ /”后面的东西的方法。 sorry about my language problems. 对我的语言问题感到抱歉。
str_replace('types.html' ,'','www.example.com/somthing/types.html'); is for if i know the file name (types.html). 用于如果我知道文件名(types.html)。

You can use this 你可以用这个

preg_replace('/([^\/]*$)/', '', 'www.example.com/somthing/types.html');

This will replace all characters after the last / 这将替换最后一个/后的所有字符

Output will be www.example.com/somthing/ 输出将是www.example.com/somthing/

You can also do this the old fashion way: 您也可以按照旧的方式进行操作:

$url = 'www.example.com/somthing/types.html';

$divided = explode( '/', $url );
array_pop( $divided );

$new_url = implode( '/', $divided );
Try this
$string = 'www.examle.com/somthing/types.html';
echo preg_replace('#\/[^/]*$#', '', $string);

If you are considering the fast and the fastest you may consider this piece of code instead preg_replace 如果您考虑最快和最快,则可以考虑这段代码,而不是preg_replace

$url = explode("/",$url);
array_pop($url);
$url = implode("/",$url);

Again it is slighly faster so do as you please :). 同样,它速度更快,所以请您:)。

Proof: http://sandbox.onlinephpfunctions.com/code/5083e02d4f171502ef1e7c87c8dd9a957ee0d8fb 证明: http : //sandbox.onlinephpfunctions.com/code/5083e02d4f171502ef1e7c87c8dd9a957ee0d8fb

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM