简体   繁体   中英

Regular Expression within URL

I've tried searching for the answer but it's a tough question to ask in the first place, here goes.

Consider the following URL(s):

  • hotels-london-kensington-5star
  • hotels-london-kensington-mayfair-5star
  • hotels-london-5star

the following would be returned using the correct regular expression:

  • london-kensington
  • london-kensington-mayfair
  • london

I'm trying to use regular expression to get the centre value(s) ONLY. I know the first and last words of the string in all cases ie 'hotels' (first) and '5star' (last).

UPDATE: I need to use regular expressions as the URL's are being routed through Codeigniters URI router. The centre part of the URI is dynamically built for search results.

Since you know the first and last words, you also know their lengths.

$out = substr($in,7,-6);

Or more generally:

$out = substr($in,strlen($begin),-strlen($end));

EDIT: If regex is required , just use /(?<=hotels-).*(?=-5star)/

For such simple cases you can use a explode()

$parts = explode('-', $string);
$wanted = array_slice($parts, 1, count($parts)-2);

Update: A regular expression. I still think it's easier to split the string into pieces manually.

~hotels-(.+)-5start~

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM