carylson
carylson

Reputation: 19

PHP regex pattern to return N slugs/chunks (separated or split on the "/" char.) as matches from a "friendly" URL?

I'm looking for a regex pattern that will return N slugs/chunks (all pieces of the URL, separated or split on the "/" char.) as matches from a "friendly" URL.

The pattern should not include the domain or a leading slash. Also, the pattern should work with an unknown number of slugs and/or slashes.

For example, some example URLs and desired returned slugs/chunks:

Finally, I need to pass this regex pattern preg_match (or similar) and have it return the results via the function's $matches parameter.

For example:

<?php preg_match($your_pattern, $friendly_url, $your_pattern_matches); ?>

... similar results can be prduced using explode().

This pattern is being used in a much more complex scenario than my little old example; requiring the use/forcing me to use regex patterns via preg_match for the solution. Basically, I'm passing preg_match a pattern of choice, which is why I need a regex pattern as opposed to simply using explode.

Your help is GREATLY appreciated!

Cheers!

Upvotes: 1

Views: 915

Answers (3)

FailedDev
FailedDev

Reputation: 26920

Sorry but I don't think you can do what you want with preg_match.

After reading the documentation

You can see that preg_match will stop at the first match. You want an array of the matches in a friendly url however this can only be achieved by multiple matches , in order to store the values in an array OR by a single match which would capture the whole thing. Both of these cases do not fit you so I am afraid that you would have to use something else than preg_match.

Upvotes: 1

onatm
onatm

Reputation: 846

First of all, check the manual of preg_split

$segments = preg_split('[/]', $uri, 0, PREG_SPLIT_NO_EMPTY);

If you insist on preg_match take a look on this:

$uri = '/foo-bar/baz';

preg_match_all('%[^/]+%', $uri, $matches);

print_r($matches);

Upvotes: 3

Clive
Clive

Reputation: 36957

Sounds like explode() would do the job without having to bother with regexes:

$matches = explode('/', $url);

Upvotes: 1

Related Questions