Austin Kregel
Austin Kregel

Reputation: 755

Replace words with words regex php

I need to be able to search a string and replace words like 'me', 'my', 'i' and replace them with words like 'you', and 'your'. Basically I need to be able to change the subjects possession.

Example

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

Where "remind me" is a command so that is ignored but 'my' should be changed to your. However what I have will changed every collection of the characters "m" and "y" to "your". So words like astronomy is now astronoyour. Which I don't want.

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);
       }
     }
   }
}

And example output from using the above functions

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

I'm sure I am going to have to create my own way to figure this out, but I figured I'd ask because I know regex is a great tool, and I am probably overlooking the solution.

Semi working demo

This demo url shows the current code that I am using and will be updated as answers come in. Please feel free to look around :)

Direct link to the string class in question: http://api.austinkregel.com/butler/string-class

Upvotes: 1

Views: 89

Answers (2)

user557846
user557846

Reputation:

<?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


?>

Upvotes: 1

nahtnam
nahtnam

Reputation: 2689

Check out PHP string replace match whole word

In that link, it shows you how to use preg_replace.

You can use something like this:

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

This code is not tested, and you may have to make some changes

Upvotes: 0

Related Questions