duankui1532 2015-09-20 11:29
浏览 16
已采纳

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

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

  • 写回答

1条回答 默认 最新

  • dongwei2030 2015-09-20 11:53
    关注
    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 OpenGL渲染效率
  • ¥60 关于网络前后端:丢包攻击、漏洞后门、渗透这些
  • ¥30 有关于html的制作个人网页
  • ¥15 stm32 lvgl+DMA,屏幕显示不全有条纹
  • ¥15 用java,swing,mysql实现模拟ATM机系统
  • ¥15 HTML5+CSS3题
  • ¥30 使用php如何制作一个国博门票抢票系统?(相关搜索:手机号|小程序)
  • ¥15 关于#数据库#的问题:每次实验都是系统直接导出数据,但是实验过程前会修改被实验件的结构类型,软件版本(如第一次实验为结构A,A01版本软件,A01版本软件)(相关搜索:数据类型)
  • ¥15 群晖docker无法连接代理服务器
  • ¥20 VBA将EXCEL数据写入JSON,中文不显示