Matías Cánepa
Matías Cánepa

Reputation: 5974

get variables from regular expresion

I have one of the following strings:

mystring
/mystring
mystring?test
/mystring?test

That is one string preceded by one optional / and followed by and optional ?test

I need to get this variables:

$string = "mystring"
$test = false / true depending if ?test is present

I'm trying to use regular expressions but I'm having trouble with the right pattern. I'm trying:

\/?(\w+)(\??\w+)

For example, for "mystring", I'm getting this:

Array
(
    [0] => /mystring
    [1] => mystrin
    [2] => g
)

This is a sample code:

<?
echo "<pre>";

$input = "/mystring";

$pattern = "/\/?(\w+)(\??\w+)/";

$matches = null;

preg_match($pattern, $input, $matches);

print_r($matches);
?>

Upvotes: 0

Views: 34

Answers (2)

Don&#39;t Panic
Don&#39;t Panic

Reputation: 41810

For a non-regex alternative if you're interested, you can use parse_url. It accepts partial URLs, and it can parse strings like those.

$components = parse_url($input);

$string is the path with leading slash removed, and $test is the equality of the query to the string 'test'.

$string = trim($components['path'], '/');
$test = isset($components['query']) && $components['query'] == 'test';

Upvotes: 1

Nabeel Khan
Nabeel Khan

Reputation: 3993

You're including the ? in catch expression.

The regex you should use: \/?(\w+)\??(\w+)?

This will use less number of steps (46 compared to 56 of your regex) hence less load on the server too.

Demo: https://regex101.com/r/98QNeh/2

Upvotes: 0

Related Questions