Home > Blockchain >  Php string condition check for plugin
Php string condition check for plugin

Time:11-01

I have that function inside on a wp all import plugin for Wordpress to import products,that takes the first value and renames to the second value, a simple mapping function.

I want simply insert an condition that checking that strings and if isn't on that strings then the new string will be $cat=uncategorized>$cat in other words if isnt on my dictionary for example $cat=cars then i want to replace to uncategorized>cars

function cat_change($cat){
    
    $cat = str_replace("XLARGE", "XL", $cat);
    $cat = str_replace("xl", "XL", $cat);
    $cat = str_replace("extralarge", "XL", $cat);
    
    
    $cat = str_replace("XXL", "2XL", $cat);
    $cat = str_replace("2XLARGE", "2XL", $cat);
    $cat = str_replace("2large", "2XL", $cat);
    $cat = str_replace("2xlarge", "2XL", $cat);
    
    $cat = str_replace("XXXL", "3XL", $cat);
    $cat = str_replace("3XLARGE", "3XL", $cat);
    $cat = str_replace("3large", "3XL", $cat);
    $cat = str_replace("3xlarge", "3XL", $cat);


    return $cat;
}

CodePudding user response:

First you can pass arrays to str_replace so all those lines can be done in one.

You can then use the $find array and explode() to search using in_array() to check at least one of the words in $find exists in the $cat string

function cat_change($cat){
    $find = ['XLARGE', 'xl','extralarge', 'XXL', '2XLARGE', '2large', '2xlarge', 'XXXL', '3XLARGE', '3large', '3xlarge'];
    $replace = ['XL','XL','XL', '2XL', '2XL','2XL','2XL','3XL','3XL','3XL','3XL'];

    $allwords = explode(' ', $cat);
    $found = FALSE;
    foreach ($find as $word){
        if (in_array($word, $allwords)){
            $found = true;
            break;
        }
    }
    if (!$found){
        return 'something else';
    }
    $cat = str_replace($find, $replace, $cat);
    return $cat;
}

$input = 'The quick XLARGE fox jumped over the 2XLARGE moon';
echo $input . PHP_EOL;
echo cat_change($input);

RESULT

The quick XLARGE fox jumped over the 2XLARGE moon
The quick XL fox jumped over the 2XL moon

Or using input that does no have any find value in it

$input = 'The quick fox jumped over the moon';
echo $input . PHP_EOL;
echo cat_change($input);

RESULTS IN

The quick fox jumped over the moon
something else
  • Related