开发者

Php trim get value characters that are not in array

开发者 https://www.devze.com 2023-03-23 03:06 出处:网络
I\'m using the codeigniter framework and utilizing theuri->segment(); function I have an array: $brand_array = array(\"Alpine\" => \"Alpine\", \"Atrend\" => \"Atrend\");

I'm using the codeigniter framework and utilizing the uri->segment(); function

I have an array:

$brand_array = array("Alpine" => "Alpine", "Atrend" => "Atrend");

if ($this->uri->segment(3) && array_key_exists($this->uri->segment(3),
                                                         $brand_array)) {
$mm = $brand_array[$this->uri->segment(3)];


    echo $mm;

    } 

I want to use PHP to trim any characters that do not equal an array value

s开发者_开发技巧o if the user types this into the url example.com/brands/DDDAlpine

I would want to trim all of those characters before Alpine

is this going to be a fairly complex function?

Will I need to use preg_replace and write my own string pattern?


Here is a solution that will accommodate an exact match, a single possibility, multiple possible matches, and will acknowledge no matches:

$brand_array = array("Alpine" => "Alpine", "Atrend" => "Atrend");

if($this->uri->segment(3))
{
    // Check for exact match
    if(array_key_exists($this->uri->segment(3),$brand_array))
    {
        $brand = $this->uri->segment(3);
    }

    // If no exact match, lets look for the brand somewhere in the uri segment
    else
    {
        $uris = array_keys($brand_array);
        $potential_matches = array();
        foreach($uris as $uri)
        {
            if(stristr($uri,$this->uri->segment(3)))
            {
                $potential_matches[] = $uri;
            }
        }

        // Check length of potential matches. If only 1, lets use it
        if(count($potential_matches) < 1)
        {
            // No match, fail or redirect
            echo 'No match';
        }
        else if(count($potential_matches) == 1)
        {
            $brand = $potential_matches[0];
        }
        else
        {
            // Show all possible matches...
            print_r($potential_matches);
        }
    }
}


I could imagine only looping through array and doing a regular expression match for every brand

<?php
$mm = '';
if ($this->uri->segment(3)) {
  foreach ($brand_array as $brand) {
    if (preg_match('/^.*' . $brand . '.*$/i', $this->uri->segment(3)) {
      $mm = $brand;
      break;
    }
  }
}
echo $mm;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号