2016-04-14 4 views
1

%sku%%any%のような2つの単語は、サイトのURL構造で使用されます。Find Wordどのphlの最初に来る

このデータはデータベースに保存されますので、どのデータが最初に来るのかを調べる必要があります。

など。以下のURL %sku%

が来以下のURLで %any%が、私は構造が一貫性のある、それは可能性になることを確認してくださいカントさらに

http://example.com/%any%/product/%sku%

最初に来るものの

http://example.com/%sku%/product/%any%

最初以下のいずれかのようになります。

私が最後に来る最初とされていたのかを確認したい..しかし %sku% and%はどんな%が `私が定義されています。..ので、私はできる

http://example.com/%sku%/product/%any%
http://example.com/%any%/product/%sku%
http://example.com/%any%/%sku%
http://example.com/product/%sku%
http://example.com/product/%any%

それらのタグが使用されることを100%確信してください。次のコードは、指定された$attributes配列の最初と最後に発生するアイテムを返します

$URL = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; 
$posOfSku=strlen($URL); 
$posOfAny=strlen($URL); 

if(strpos($URL ,'%sku%') !== false) { 
    $posOfSku = strpos($URL ,'%sku%'); 
} 
if(strpos($URL ,'%any%') !== false) { 
    $posOfAny= strpos($URL ,'%any%'); 
} 

$result = ($posOfAny < $posOfSku) ? 'any came 1st' : 'sku came 1st'; 
echo $result; 

答えて

2

同じようstrpos

なものを使用。

$string = 'http://example.com/%sku%/product/%any%'; 

// values to check for 
$attributes = ['%sku%', '%any%']; 

$results = array(); 
foreach($attributes as $attribute) 
{ 
    // Get position of attribute in uri string 
    $pos = strpos($string, $attribute); 

    // if it exists we add it to the array with the position 
    if($pos) 
    { 
     $results[$attribute] = $pos; 
    } 
} 

// Get the first occuring attribute 
$firstOccuringAttribute = array_search(min($results), $results); 

// Get the last occuring attribute 
$lastOccuringAttribute = array_search(max($results), $results); 

これはもう少し読みやすいものにリファクタリングすることができます

$uri = 'http://example.com/%sku%/product/%any%'; 
$attributes = ['%sku%', '%any%']; 

$lastAttribute = getLastAttribute($uri, $attributes); 
$firstAttribute = getFirstAttribtue($uri, $attributes); 


function getAttributeWeighting($uri, $attributes) 
{ 
    $results = array(); 
    foreach($attributes as $attribute) 
    { 
     $pos = strpos($uri, $attribute); 

     if($pos) 
     { 
      $results[$attribute] = $pos; 
     } 
    } 

    return $results; 
} 

function getFirstAttribute($uri, $attributes) 
{ 
    $attributeWeighting = getAttributeWeighting($uri, $attributes); 

    return array_search(min($attributeWeighting), $attributeWeighting); 
} 

function getLastAttribute($uri, $attributes) 
{ 
    $attributeWeighting = getAttributeWeighting($uri, $attributes); 

    return array_search(max($attributeWeighting), $attributeWeighting); 
} 
+0

いくつかのポイント。最後に来る答えは表示されません。引数以上のものがあり、 '%sku%'や '%any%'以外のものであれば、余分なリファクタリングも必要です。 – Jeemusu

+0

それは 'ちょうどプロトタイプです。あなたは同じロジックを維持しながら配列とループを使用することができます。私はOPがそれを自分で行うことができると思います...彼はちょうどコード全体と新しい要件ではなく方向性を必要としました。 –

+0

あなたの答えは元の質問のいくつかのuri要件では機能しません。 '%any%'文字列がURLにない場合、 '$ posOfAny'は' 0'に等しくなります。したがって、 '$ result'は' 'any come came 1st '' 'になります。 – Jeemusu

3

+0

これは、questioneérが一致する針をさらに追加したい場合には、はるかに簡単です。答えでなければならない。 – andersfylling

関連する問題