Lorenz
Lorenz

Reputation: 51

Need help remove part from url

I need to get part from url, i know lots tutorial in this website but i'm still unable to get it...

this sample url :

https://www.domain.com/want-to-keep-35/?idku=rbxbbgh3dKqn

I only need this part only from that url, without domain, slash and end url

want-to-keep-35

already try this code :

preg_replace('|https?://www\.[a-z\.0-9]+|i', '', $serp);

but not working. let me know if anyone in here can help me and thanks

Upvotes: 1

Views: 397

Answers (4)

JLavoie
JLavoie

Reputation: 17626

Only if you know the domain name, why not simply use:

$url = 'https://www.domain.com/want-to-keep-35/?idku=rbxbbgh3dKqn';
$keep = explode("https://www.domain.com/", $url);
$keep2 = explode("/", $keep[0]);

$keep[0] will contain 'want-to-keep-35/?idku=rbxbbgh3dKqn'

$keep2[0] will contain 'want-to-keep-35'

Upvotes: 0

Josua M C
Josua M C

Reputation: 3158

Try this

<?php

$url = 'https://www.domain.com/want-to-keep-35/?idku=rbxbbgh3dKqn';

$parsedURL = parse_url($url);
echo "<pre>";
var_dump(parse_url($url));
echo "</pre>";


$result = trim($parsedURL['path'], '/');
echo $result;

Upvotes: 0

someOne
someOne

Reputation: 1675

If it's that simple, you may use the following simple approach to get what you want:

$url = 'https://www.domain.com/want-to-keep-35/?idku=rbxbbgh3dKqn';
$re = '#https://www\..*?\..*?/(.*?)/#i';

preg_match($re, $url, $matches);
echo $matches[1]; // want-to-keep-35

Upvotes: 1

Cohan
Cohan

Reputation: 4564

If you use two patterns and run them in succession, you will be able to eliminate the first part and then the second part.

pattern 1 will find http or https and then the ://. Then it will read everything that is not a slash until the first slash effectively removing the domain from the url. Finally, it will lump in the the slash you don't want.

pattern 2 will take from a string starting with want-to... and find the first slash and everything after it.

$url = "https://www.domain.com/want-to-keep-35/?idku=rbxbbgh3dKqn";
$pattern1 = "/https?\:\/\/[^\/]+\//";
$pattern2 = "/\/.*/";
$url = preg_replace($pattern1, '', $url);
$url = preg_replace($pattern2, '', $url);
echo $url;

yields

want-to-keep-35

You can also pass in an array of patterns and it will evaluate them in order

$url = "https://www.domain.com/want-to-keep-35/?idku=rbxbbgh3dKqn";
$patterns = array("/https?\:\/\/[^\/]+\//", "/\/.*/");
$url = preg_replace($patterns, '', $url);
echo $url;

Upvotes: 0

Related Questions