2014-01-11 228 views
0

我試圖提取字在最後/和倒數第二個/之間的最後和倒數第二次數之間提取字符。正則表達式字符

  1. $string = https://ss1.xxx/img/categories_v2/FOOD/fastfood(想更換$stringfood
  2. $string = https://ss1.xxx/img/categories_v2/SHOPS/barbershop(想更換$stringshops

我是新來的正則表達式,並試圖/[^/]*$ - 當然,這是後返回萬萬最後/ ..任何幫助將不勝感激..謝謝!

我正在使用PHP。

回答

0

您可以使用此:

$result = preg_replace_callback('~(?<=/)[^/]+(?=/[^/]*$)~', function ($m) { 
    return strtolower($m[0]); }, $string); 

模式的細節:

~   # pattern delimiter 
(?<=/)  # zero width assertion (lookbehind): preceded by/
[^/]+  # all characters except/one or more times 
(?=/[^/]*$) # zero width assertion (lookahead): followed by /, 
      # all that is not a/zero or more times, and the end of the string 
~   # pattern delimiter 
+0

他想要抽取,而不是替代。 – Barmar

1

用途:

preg_match('#/([^/]*)/[^/]*$#', $string, $match); 
echo $match[1]; 

您還可以使用:

$words = explode('/', $string); 
echo $words[count($words)-2]; 
+0

我還扔['parse_url($字符串,PHP_URL_PATH)'](http://uk1.php.net/parse_url)中選擇2理智的地方:) – Emissary

0

正則表達式:

(\w+)(/[^/]+)$ 

PHP代碼:

<?php 
    $string = "https://ss1.xxx/img/categories_v2/FOOD/fastfood"; 
    echo preg_replace("@(\w+)(/[^/]+)[email protected]", "food$2", $string); 
    $string = "https://ss1.xxx/img/categories_v2/SHOPS/barbershop"; 
    echo preg_replace("@(\w+)(/[^/]+)[email protected]", "shops$2", $string); 
?>