dtx6087 2015-05-05 13:36
浏览 76
已采纳

PHP替换多个单词

So I want to remove everything but some words. I want to keep for an example "car", "circle" and "roof". But remove everything else in a string.

Let's say the string is "I have a car with red one circle at the roof". I wantr to remove everything but "car", "circle" and "roof".

I know there's this one:

$text = preg_replace('/\bHello\b/', 'NEW', $text);

But I can't figure out how to do it with multiple words. I've done this below, but it does the opposite.

$post = $_POST['text'];
$connectors = array( 'array', 'php', 'css' );

$output = implode(' ', array_diff(explode(' ', $post), $connectors));

echo $output;
  • 写回答

3条回答 默认 最新

  • drfm55597 2015-05-05 14:02
    关注
    <?php
    $wordsToKeep = array('car', 'circle', 'roof');
    $text = 'I have a car with red one circle at the roof';
    
    $words = explode(' ', $text);
    $filteredWords = array_intersect($words, $wordsToKeep);
    
    $filteredString = implode(' ', $filteredWords);
    

    $filteredString would then equal car circle roof.

    See http://php.net/manual/en/function.array-intersect.php

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

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料