简体   繁体   中英

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 <a href="animals.html" . somthing,somthing2 are files every file contains links in types.html and files like animals.html in the same folders. when i get it with dom it shows only "animals.html" but i want to get "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.

i just need a way to remove "types.html" from www.example.com/somthing/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).

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/

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

$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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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