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;
精彩评论