Search code examples
regexwordpressmod-rewritepermalinks

Is it possible to make ineffective a character in regex


I'm trying to write wordpress pretty permalinks regex.

I have following urls. I need 2 matches,

1st : last word between / and / before get/ 2nd : string which is start with get/ Url's may be like these

http://localhost/akasia/yacht-technical-services/yacht-crew/get/gulets/for/sale/

Here I need "yacht-crew" and "get/gulets/for/sale/"

http://localhost/akasia/testimonials/get/motoryachts/for/sale/

here I need "testimonials" and get/motoryachts/for/sale/

http://localhost/akasia/may/be/lots/of/seperator/but/ineed/last/get/ships/for/rent/

here I need "last" and get/ships/for/rent/

$url1 = 'somepage/get/gulets/for/sale'; // I need somepage and get/gulets/for/sale
$url2 = 'somepage/subpage/get/motoryachts/for/rent'; // I need subpage and get/motoryachts/for/rent
$url3 = 'may/be/unlimited/directories/but/i/need/here/get/ships/for/sale'; // I need here and get/ships/for/sale
$url4 = 'services/get/gulets/for/sale'; // I need services and get/gulets/for/sale
$regex = '([^\/]+?)\/(get\/.+)';

// I can not change anything below.
preg_match("#^$regex#", $url4, $matches);
echo "<pre>";
print_r($matches);
echo "</pre>"

I catch $url4 but Could not $url1, $url2, $url3

I appreciate if someone help.


Solution

  • Use \K to discard the previously matched characters from printing at the final.

    .*(?:\/|^)\K([^\/]+?)\/(get\/.+)
    

    DEMO