dongyao4003 2011-11-09 11:28
浏览 21
已采纳

用preg_replace替换字符串中的多个单词似乎不起作用

Code:

$testing="sniper this and sniper that";
$connectors=array('and', 'now', 'but', 'still', 'so', 'only', 'therefore', 'moreover', 'besides', 'consequently','nevertheless', 'for', 'however', 'hence', 'either', 'or', 'neither', 'nor', 'both', 'also','while', 'then', 'who', 'which', 'that', 'although', 'though', 'since', 'until', 'as', 'if','after', 'before', 'how', 'once', 'when', 'lest', 'why', 'unless', 'because', 'till', 'where', 'whether','the', 'a', 'an','about', 'above', 'across', 'after', 'against', 'along', 'among', 'around', 'at', 'before', 'behind','below', 'beneath', 'beside', 'between', 'beyond', 'but', 'by', 'despite', 'down', 'during', 'except','for', 'from', 'in', 'inside', 'into', 'like', 'near', 'of', 'off', 'on', 'onto', 'out', 'outside', 'over',
        'past', 'since', 'through', 'throughout', 'till', 'to', 'toward', 'under', 'underneath', 'until', 'up', 'upon','with', 'within', 'without','who', 'whom', 'whose', 'which', 'that', 'this', 'these', 'those', 'I', 'Me', 'You', 'He', 'him', 'she','her', 'it', 'we', 'us', 'they', 'them', 'Mine', 'Yours', 'His', 'Hers', 'Its', 'Ours', 'Theirs', 'whoever','whomever', 'whichever', 'myself', 'yourself', 'himself', 'herself', 'itself','ourselves', 'yourselves', 'themselves');

foreach($connectors as $word)
{
    $pattern="/".strtolower($word)."/";
    $data=preg_replace($pattern,"/ /", $testing);
}
echo $data."<br>";
echo $testing;

Output:

sniper this and sniper that

sniper this and sniper that

Expected output:

sniper this and sniper that

sniper sniper

What am I doing wrong?

  • 写回答

3条回答 默认 最新

  • dongyan7988 2011-11-09 11:34
    关注

    Try with:

    $testing = "sniper this and sniper that";
    $connectors = array( /* your data */ );
    
    $output = implode(' ', array_diff(explode(' ', $testing), $connectors));
    

    Case insensitive way:

    $output = implode(' ', array_udiff(explode(' ', $testing), $connectors, 'strcasecmp'));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输