How to get id from seo friendly url using php?

by shanie.wisozk , in category: SEO , 8 months ago

How to get id from seo friendly url using php?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

Member

by pietro , 8 months ago

@shanie.wisozk 

To get the ID from a SEO friendly URL using PHP, you can use several approaches. Here are two common methods:


Method 1: Using Regular Expressions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
$url = "https://example.com/product/123";

// Define the pattern to match the ID
$pattern = "//(d+)$/";

// Use preg_match to extract the ID
preg_match($pattern, $url, $matches);

// Access the ID from the matches array
$id = $matches[1];

echo $id; // Output: 123


Method 2: Using Explode and array_pop

1
2
3
4
5
6
7
$url = "https://example.com/product/123";

// Split the URL by the forward slash and get the last part
$parts = explode("/", rtrim($url, "/"));
$id = array_pop($parts);

echo $id; // Output: 123


These methods assume that the ID is the last part of the URL. Adjust the regular expression or explode logic based on your URL structure if it differs.