douhan1992 2011-01-05 05:15 采纳率: 100%
浏览 62
已采纳

麻烦在PHP中使用str_replace和preg_replace

I am having trouble with string manipulation in php. I am writing a function that with take a string parameter that has words separated with either " " or "_". I want the function to remove all non alphabetic characters and return the words separated with a "-". This is what I have so far:

function cleanCategoryForUrl($strCategory){
    $newCategory = str_replace('_', '-', $strCategory); //First replacement
    echo ($newCategory);
    $newCategory = str_replace(' ', '-', $newCategory); //Second replacement
    echo ($newCategory);
    $newCategory = preg_replace('/[^a-z-]/i', '', $strCategory); //Final replacement
    echo ($newCategory);
    return $newCategory;
}

The first and second replacements will get make the words separated with "-" instead of " " or "_". The final replacement will get red of all characters that are not alphabetic or a "-".

But when I test the code, I get unexpected results after the final replacement.

With an input of "Home_Health" I get this printed:

Home-Health
Home-Health
HomeHealth

The first two outputs are as expected, but third one removed the "-" (which shouldn't have happened). I suspect something is wrong with my regex pattern, but it words fine when I test it on http://gskinner.com/RegExr/. I am new to using regex and cant figure out what is wrong. Please Help

  • 写回答

1条回答 默认 最新

  • doupingpeng7567 2011-01-05 05:21
    关注

    Everything seems fine but just a problem in parameter you passing in preg_replace. Instead of passing $newCategory you are passing $strCategory.

    Just try with below one,

    function cleanCategoryForUrl($strCategory){
        $newCategory = str_replace('_', '-', $strCategory); //First replacement
        echo ($newCategory."<br/>");
        $newCategory = str_replace(' ', '-', $newCategory); //Second replacement
        echo ($newCategory."<br/>");
        $newCategory = preg_replace('/[^a-z-]/i', '', $newCategory); //Final replacement
        echo ($newCategory."<br/>");
        return $newCategory;
    }
    

    Or else you can use this one.

    function cleanCategoryForUrl($strCategory){
        $newCategory = preg_replace('/[_ ]/', '-', $strCategory); //Final replacement
        $newCategory = preg_replace('/[^a-z-]/i', '', $newCategory); //Final replacement
        echo ($newCategory."<br/>");
        return $newCategory;
    }
    

    Hope this will help,

    Thanks!

    Hussain.

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

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器