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条)

报告相同问题?

悬赏问题

  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择
  • ¥15 这款软件是什么?需要能满足我的需求
  • ¥15 SpringSecurityOauth2登陆前后request不一致