YahyaE YahyaE - 3 months ago 16
PHP Question

PHP preg_match for getting a string part after the given optional substrings

I have several urls such as below and those contains

-XX-
letter and following
xxxxxxxxx
key in the end of the url.

http://vayes-eys.dev/shoe-for-ladies/high-hields/7-pont-with-silver-stripes-PD-0a8564q56


or

http://vayes-eys.dev/news/europe/england/cricket-news/josh-darpant-is-on-the-way-to-rome-NS-e3q3s2wq4q


What I want to do is; first to check if
-NS-
,
-PD-
or
-SP-
exist in url, then get the
-XX-
part and the part after it,for example:
e3q3s2wq4q
.

What I have done so far is:

$path = "shoe-for-ladies/high-hields/7-pont-with-silver-stripes-PD-0a8564q56"

if (preg_match('/-PD-|-NS-|-SP-/',$path)) {
preg_match("/(?<=(-PD-|-NS-|-SP-)).*/", $path, $match);
print_r($match);
}


This gives me the following array but I am not sure if it is the right way.

array(
0 => 0a8564q56
1 => -PD-
)


What I need is
PD
and
0a8564q56
. Thanks for any help.

Answer

You may use

'~-(NS|PD|SP)-([^-/]+)~'

or

'~-(NS|PD|SP)-([A-Za-z0-9]+)~'

See the regex demo

Details:

  • - - a literal hyphen
  • (NS|PD|SP) - Group 1 capturing one of the values: NS, PD or SP
  • - - a hyphen
  • ([^-/]+) - 1 or more characters other than - and / (the delimiters). If you only have letters and digits there, you may just use [a-zA-Z0-9]+ instead.

PHP demo:

$path = "shoe-for-ladies/high-hields/7-pont-with-silver-stripes-PD-0a8564q56";
preg_match('~-(NS|PD|SP)-([A-Za-z0-9]+)~', $path, $match);
print_r($match);

Your values are in Group 1 and 2.