查找php中排名第一的单词


Find Word Which comes first in php

我有两个单词,如%sku%%any%,将在网站url结构中使用。

这些数据将保存在数据库中,我需要找出哪个先出现。

例如

在下面的url中,%sku%首先出现

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

而在下面的url中%any%首先出现

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

此外,我不能确定结构是否一致——它可能像下面的任何一个一样:

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%

我想查一下哪个先来,哪个最后来。。但是%sku% and%any%`是由我定义的。所以我可以100%确定这些标签将被使用。

以下代码将返回指定$attributes数组中出现的第一个和最后一个项。

$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);
}

只需使用strpos

类似于:

$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;