kristjanzzz
kristjanzzz

Reputation: 67

Get prefix substring from the parent directory of a URL string

http://www.webpage.ee/xxx-galerii/event-02-02-13

How can I get "xxx" part out of that URL using PHP? There is always "ee/" on the left side and "-galerii" on the right side.

Upvotes: -1

Views: 97

Answers (2)

mickmackusa
mickmackusa

Reputation: 48071

Parse the URL with url_parse(), then extract the prefix after the leading slash until a hyphen is encountered. (Demo)

$url = 'http://www.webpage.ee/xxx-galerii/event-02-02-13';

sscanf(parse_url($url, PHP_URL_PATH), '/%[^-]', $prefix);
echo $prefix;
// xxx

Or use strtok() to return the first non-empty substring before a forward slash or hyphen. (Demo)

echo strtok(parse_url($url, PHP_URL_PATH), '/-]');

Upvotes: 0

KingCrunch
KingCrunch

Reputation: 132071

$path = parseurl($url, PHP_URL_PATH);
list($xxx) = explode('-', $path, 2);

Upvotes: 4

Related Questions