将单词替换为regex-php


Replace words with words regex php

我需要能够搜索字符串并替换像"me"、"my"、"I"这样的单词,然后用像"you"answers"your"这样的词替换它们。基本上我需要能够改变主体的占有率。

示例

User input: "Can you remind me to feed my dog tonight?"
Response  : "Sure I can remind you to: feed your dog tonight"

其中"提醒我"是一个被忽略的命令,但"我的"应该改为"你的"。然而,我将把每个字符集"m"answers"y"改为"your"。所以像astronomy这样的词现在是astronoyour。我不想要。

public static function userToServer($string){
   $pos = array(' me '=>'you', ' i '=>'you','we'=>'we','us'=>'you','you'=>' i ', ' my '=>'your');
   foreach($pos as $key => $value){
      if(strpos($string, $key) !== false){
          $result = str_replace ($key, $value, $string );
          print_r($result);
          return  $result;
      }
   }
  return null;
}
public static function parse($string, $commands){
  foreach($commands as $c){
     if(stripos($string,$c) !== false){
        $params = explode($c, $string);
        $com[$c] =$params[1];
     }
   }
   if(isset($params)){
     foreach($com as $key => $value){
       if($key ==='remind me to'){
          //$user->addEventToCalender($value);
          //echo $value;
          echo 'Okay, I will remind you to '.String::userToServer($value);
       }
     }
   }
}

以及使用上述函数的示例输出

Using $_GET['input'] as $input
Original: Will you remind me to secure funds for my business
Response: Okay, I will remind you to secure funds for my byouiness

我确信我将不得不创建自己的方法来解决这个问题,但我想我会问,因为我知道regex是一个很好的工具,我可能忽略了解决方案。

半工作演示

这个演示url显示了我正在使用的当前代码,并将随着答案的到来而更新。请随意查看:)

到有问题的字符串类的直接链接:http://api.austinkregel.com/butler/string-class

<?php

  function userToServer($string){
      $in=array('#'bcat'b#','#'bdog'b#');
      $out=array('fish','frog');
      $string=preg_replace($in,$out,$string);  
      return $string;
    }

   echo userToServer("cat eat dog but not doge");  //fish eat frog but not doge

?>

查看PHP字符串替换匹配的完整单词

在该链接中,它将向您展示如何使用preg_replace

你可以使用这样的东西:

$phrase = preg_replace('/'bmy'b/i', 'your', $phrase);

此代码未经过测试,您可能需要进行一些更改