I'm trying to get the function to replace strings which contain "T-Shirt" with the phrase "Clothing > Tops & T-Shirts" and Stings which contain "Shirt" with "Clothing > Shirts,"
However, just now all of the strings fall into the "Clothing > Shirts" category. I believe it's to do with the code not considering the dash between T and Shirt. Could someone people tell me how to make it differentiate between the two?
function replaceItems($value) {
//here are predefined values
$predefined = array(
array(
'search' => 'T-Shirt, Top',
'replaceWith' => 'Clothing > Tops & T-Shirts'
),
array(
'search' => 'Shirt, Polo',
'replaceWith' => 'Clothing > Shirts'
)
);
//search and replace
$found = false;
foreach($predefined as $item) {
$search = array_map('trim', explode(',', $item['search']));
foreach($search as $s) {
if (preg_match("/\b".strtolower($s).
"\b/i", strtolower($value))) {
$found = true;
$value = $item['replaceWith'];
break;
}
}
}
return ($found) ? $value : "";
}
Much Appreciated
function replaceItems($value) {
$found = false;
$patterns = array('/T-Shirt, Top/',
'/Shirt, Polo/');
$replacements = array('Clothing > Tops & T-Shirts',
'Clothing > Shirts');
$result = preg_replace($patterns, $replacements, $value);
if($result != $value){
//preg_replace returns the changed string if anything was
//changed so here I check if the string is different from the original
$found = true;
}
return ($found) ? $result : "";
}
echo replaceItems("lorem ipsum, T-Shirt, Top lorem ipsumother test");
//returns 'rem ipsum, Clothing > Tops & T-Shirts lorem ipsumother test'
Put the words you want to replace in the $patterns array and the replacements in the replacements array. Just make sure they are on the same key.