2013-07-23 43 views
0

我有這個網址:../foo::bar{2}233{13}171{1}1{20}0.html從大括號獲得網址PARAM

參數是{},值後面。

有了這個,我能得到一個參數 - 儘管花括號:

if (false !== strpos($url,'{2}')) { 
     echo 'success'; 
    } else { 
     echo 'error'; 
} 

我想要得到的{}背後都有價值。

+0

是鍵和值始終數字? – hank

+0

是的,他們是。謝謝。 – user1957345

回答

1

使用preg_match_all()

$str = '../foo::bar{2}233{13}171{1}1{20}0.html'; 

$pattern = "/\{\d+\}/"; 

preg_match_all($pattern, $str, $matches); 

$prevStart = 0; 
foreach($matches[0] as $match) 
{ 
    $matchLen = strlen($match); 
    $matchPos = strpos($str, $match, $prevStart); 

    // Try to find the position of the next open curly brace 
    $openCurlyPos = strpos($str, '{', $matchPos + $matchLen); 

    // In case there is none found (.html comes up next), search for the . instead 
    if($openCurlyPos === false) 
     $openCurlyPos = strpos($str, '.', $matchPos + $matchLen); 

    $length = $openCurlyPos - ($matchPos + $matchLen); 

    $prevStart = $openCurlyPos; 
    echo $match.': '.substr($str, $matchPos + $matchLen, $length).'<br />'; 
} 

/* 
Result: 

{2}: 233 
{13}: 171 
{1}: 1 
{20}: 0 
*/ 

我知道這種方式可能是相當多餘的,但我不知道如何使用正則表達式來做到這一點嘗試。這對於人們來說似乎也更簡單。

+0

謝謝!現在我得到所有的參數。我有什麼如此添加以獲得它們的值? – user1957345

+0

@ user1957345請參考我的更新回答。 – MisterBla

+0

這就是它 - 謝謝! – user1957345

0

使用preg_match_all您可以提取鍵和值,這裏是一個樣例模式;

$matches = null; 
$returnValue = preg_match_all('/\\{(\\d+)\\}(\\d+)\\b/', '../foo::bar{2}233{13}171{1}1{20}0.html', $matches, PREG_SET_ORDER); 

如果我們忽略了雙重轉義,它的作用如下:

  • 查找{
  • 1個或多個數字,直到}
  • 1個或多個數字,直到一個字邊界出現
0

嘗試。

$pieces = explode("}", $str); 

獲取所有奇數索引元素。

$pieces[1],$pieces[3],$pieces[5] 

等等