Php 区分带破折号和不带破折号的字符串
我正在尝试使用函数将包含“T恤”的字符串替换为短语“衣服>上衣和T恤”,并将包含“衬衫”的Stings替换为“衣服>衬衫” 然而,刚才所有的字符串都属于“衣服>衬衫”类别。我相信这与代码有关,不考虑T恤和衬衫之间的破折号。有人能告诉我如何区分这两者吗Php 区分带破折号和不带破折号的字符串,php,wordpress,Php,Wordpress,我正在尝试使用函数将包含“T恤”的字符串替换为短语“衣服>上衣和T恤”,并将包含“衬衫”的Stings替换为“衣服>衬衫” 然而,刚才所有的字符串都属于“衣服>衬衫”类别。我相信这与代码有关,不考虑T恤和衬衫之间的破折号。有人能告诉我如何区分这两者吗 function replaceItems($value) { //here are predefined values $predefined = array( array( 'sear
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 : "";
}
非常感谢
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'
将要替换的单词放入$patterns数组,并将替换项放入replacements数组。只要确保它们在同一把钥匙上就行了