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 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题