0

Hello, I have urls like this:
http://site/search/region,state
and
http://site/type/mytype

I need to extract the last part and echo this. I used code below and for the first url it returns "region,state" (but I only need the last part). And what if behind the url is another character like a slash or the equal sign?
btw: The second url is simply okay. But how do I use basename or explode to also remove the comma?
Preferably I want to use this in a function.

<?php $urlstring = $_SERVER["REQUEST_URI"]; 
                   echo basename($urlstring);
                   $urlstring = explode('/', $urlstring);
                   $last = array_pop($urlstring);
                   echo $last ;
                ?>

Edited by mjsmitten

3
Contributors
8
Replies
29
Views
4 Years
Discussion Span
Last Post by mjsmitten
0

Have you tried parse_url ? You can explode again on the comma if you like, but not on both at once.

Edited by pritaeas

0

Instead of explode you can use preg_split here to split on the basis of mutiple delimiters.It will return array. http://php.net/manual/en/function.preg-split.php

The first parameter is regular expression and second is data you want to split.In your case it is URL.

 $urlstring = preg_split( "/([,]|[\/])/", $urlstring );
0

Parse url will give me "region,state" same as basename does.
I just want to use a part of url after these possible characters: = / ,
I thought I use array inside the explode/basename or parse url. But don't exactly know how.

0

Oh, so basically everything after the last slash, comma or equal sign?

$result = preg_match('%[/,=](.*?)$%', $yourUrl, $matches);
0

My code is now Working! with this. Thank you so much! :

<?php  
     $urlstring = basename($_SERVER["REQUEST_URI"]);
     $urlstring = preg_split( "/([,]|[=]|[\/])/", $urlstring );
     $last = array_pop($urlstring);
     echo $last ;
?>

Can I just place this in a function like so?

 <?php function urlstring(){
     $urlstring = basename($_SERVER["REQUEST_URI"]);
     $urlstring = preg_split( "/([,]|[=]|[\/])/", $urlstring );
     $last = array_pop($urlstring);
     echo $last ;
}
?>
0

One more question about this result echo $last : if the returned word(s) have a space in between it echos "word%20word". How do I remove this %20?

0

So this is my final working function with help from all of you. Thanks!

<?php 
// takes base part of url, strips after characters, then encode and echo
function urlstring(){
$urlstring = basename($_SERVER["REQUEST_URI"]);
$urlstring = preg_split( "/([,]|[=]|[\/])/", $urlstring );
$last = array_pop($urlstring);
echo utf8_decode(urldecode($last)) ;
} 
?>
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.