2015-09-20 11:29



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(
            'search' => 'T-Shirt, Top',
            'replaceWith' => 'Clothing > Tops & T-Shirts'
            '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'];
    return ($found) ? $value : "";

Much Appreciated

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • dongwei2030 dongwei2030 6年前
    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.

    点赞 评论 复制链接分享