dsbgltg159136540 2012-07-21 12:49
浏览 53
已采纳

删除字符串中的字符串

The problem I'm encountering with this is if I have single characters in the array $wordstodelete it then deletes them from words in the $oneBigDescription.

$oneBigDescription = str_replace ( $wordstodelete, '', $oneBigDescription);

So it makes it look like this:

array (size=51)
  'blck' => int 5
  'centrl' => int 6
  'clssc' => int 6
  'club' => int 10
  'crs' => int 54
  'deler' => int 7
  'delers' => int 5
  'engl' => int 6
  'felne' => int 8
  'gude' => int 5
  'hot' => int 5
  'jgur' => int 172
  'jgurs' => int 5
  'lke' => int 6

Is there a way to only delete the single character from $oneBigDescription if it is on its own?

  • 写回答

3条回答 默认 最新

  • douyong6589 2012-07-21 12:54
    关注

    $oneBigDescription = preg_replace("/\b$wordstodelete\b/", '', $oneBigDescription);

    /b should look for word boundaries to ensure it's an isolated word when one character is used.

    EDIT: Didn't quite read that right - this is more assuming you're looping over $wordstodelete as an array of words.

    So, something like this:

    $desc = "blah blah a b blah";
    $wordstodelete = array("a", "b");
    foreach($wordstodelete as $delete)
    {
        $desc= preg_replace("/\b$delete\b/", "", $desc);
    }
    

    EDIT2: Wasn't quite happy with this, so refined slightly:

    $arr = "a delete aaa a b me b";
    $wordstodelete = array("a", "b");
    $regex = array();
    foreach($wordstodelete as $word)
    {
        $regex[] = "/\b$word\b\s?/";
    }
    $arr = preg_replace($regex, '', $arr);
    

    This account for taking out the following space, which in HTML isn't usually an issue when rendered (since consecutive spaces aren't generally rendered), but still a good idea to take it out. This also creates an array of regex expressions up front, which seems a bit nicer.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启