簡體   English   中英

用單詞regex php替換單詞

[英]Replace words with words regex php

我需要能夠搜索字符串並替換諸如“ me”,“ my”,“ i”之類的單詞,並將其替換為諸如“ you”和“ your”之類的單詞。 基本上,我需要能夠更改主題資產。

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

其中“提醒我”是一個命令,因此可以忽略,但應將“我的”更改為您的命令。 但是,我將把字符“ m”和“ y”的每個集合更改為“ your”。 因此,像astronomy這樣的詞現在已astronoyour 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是一個很好的工具,而且我可能會忽略解決方案。

半工作演示

此演示網址顯示了我正在使用的當前代碼,並將在收到答案時進行更新。請隨時查看:)

直接鏈接到有問題的字符串類: 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);

此代碼未經測試,您可能需要進行一些更改

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM