区分带有和没有短划线的字符串

时间:2015-09-20 11:29:55

标签: php wordpress

我正在尝试使用短语“Clothing> Tops& T-Shirts”替换包含“T-Shirt”的字符串的功能和包含“Shirt> Shirts”的“Shirt”的Stings

然而,刚才所有的琴弦都属于“服装>衬衫”类别。我认为这与代码没有考虑T和衬衫之间的差距有关。有人可以告诉我如何区分这两者吗?

  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 : "";
}

备受赞赏

1 个答案:

答案 0 :(得分:0)

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数组中,替换为替换数组中的替换项。只要确保它们在同一把钥匙上。