Jump to content

[SOLVED] Grabbing a section of a URL


Canman2005

Recommended Posts

Hi all

 

I have a URL which looks like

 

http://www.domain.com/165-products-electronic-music.html

 

Is it possible to grab a section of that URL and set it as a variable

 

the part I want to grab is the number, so with the example above it woud be

 

165

 

or of the URL was

 

http://www.domain.com/765-apple-desktop.html

 

it would grab

 

765

 

Any help would be great

 

thanks in advance

 

ed

Link to comment
https://forums.phpfreaks.com/topic/173244-solved-grabbing-a-section-of-a-url/
Share on other sites

you can grab variables from URLs using the $_get[] method you can send variables from one page to another

 

e.g you searched for a user then when u click the usersname in sends you to profile.php what you need to do is send ?profile=Danny to profile.php then Danny would be the varable

 

Hi,

Firstly either your server needs to be configured to parse html pages as php (can be done via htaccess) or you need to change your extensions to .php.

 

Secondly, assuming that the numeric value is always in the same place (ie first in your exampes) and that they are sperated by a hyphen you could do this:

//  get the file name from the url (note - there are several ways to get this)
$file=basename($_SERVER["PHP_SELF"]);

// split $file up using the hyphen - creates an array
$file_parts=explode("-",$file);

//define the first item in the array as your variable (maybe add controls to check it is numeric)
$your_var=$file_parts[0];

 

Hope that helps :)

 

Chris

$_SERVER["PHP_SELF"] might return a slash or two, so it might be useful to use trim as well.

 

<?php
$file= $_SERVER["PHP_SELF"];

// split $file up using the hyphen - creates an array
$file_parts = explode("-", trim($file, "/"));

//define the first item in the array as your variable (maybe add controls to check it is numeric)
$your_var = $file_parts[0];

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.