dprntkxh703029 2012-04-03 01:24
浏览 45
已采纳

PHP如何替换字符串中的确切单词

I have this php code

 $filename = "verbs.php"; //  http://alylores.x10.mx/vega/verbs2.php  
 $handle = fopen($filename, "r");  
 $verbs = fread($handle, filesize($filename));  
 fclose($handle);

and i used PHP explode() function

to split the words into array

$verbslist = explode(",", $verbs);

and i also have a string, like:

$sentence = "Where is Phisz' dog?";

and then i used the str_replace() function to remove the verbs and some specifice words from the sentence, so that the only left will be the subject(s).

$newsentence = str_replace($verbslist,"",$sentence);

but the result is:

new Sentence: Phz' dog? // the is on Phisz was also removed.

and i figured out that the problem is that the Phisz words contain is which was also removed with the str_replace().

what i want is how can i remove the words/vebs from the sentence without affecting other words. I mean removing the EXACT VERB/WORD..... and in case insensitive...

that the expected result will be like this

new Sentence: Phisz' dog?

  • 写回答

2条回答 默认 最新

  • dongma7796 2012-04-03 01:30
    关注

    Using a regular expression like /\bword\b/ will replace only the word as a whole. \b denotes a word boundary. So you can do something like this:

    foreach ($verblist as &$verb) {
        $verb = '/\b' . preg_quote($verb, '/') . '\b/';
    }
    
    $newsentence = preg_replace($verblist, '', $sentence);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答