【问题标题】:string replace php - one word to more words字符串替换 php - 一个词到多个词
【发布时间】:2010-12-01 20:23:10
【问题描述】:

大家好,我需要在 php 中进行特殊类型的字符串替换。 我需要用两个不同的其他词替换一个词。

例如:在字符串“Hi mom, hi dad”中,我需要自动将单词“hi”替换为另外两个不同的单词,例如“mary”和“john”。因此,如果只有一次出现“Hi”,则仅替换为“mary”,但如果出现不止一次,则使用所有单词的关联。

因此,根据单词出现的次数,再替换一个单词。 感谢所有可以帮助我的人!

【问题讨论】:

  • 一个问题,假设你有“嗨妈妈,嗨爸爸,嗨爷爷”,它会用玛丽和约翰重新开始,还是彼得。

标签: php string query-string


【解决方案1】:

preg_replace_callback 让您控制每次更换。

【讨论】:

  • 如果您问我,这就是您问题的解决方案,请查看我的示例以查看您正在搜索的内容的工作版本。 (+1)
【解决方案2】:

您可以通过多次调用preg_replace 来完成此操作,为每次调用指定限制为 1:

$string = "Hi mom, hi dad";

preg_replace('/hi/i', 'mary', $str, 1); // "mary mom, hi dad"
preg_replace('/hi/i', 'john', $str, 1); // "mary mom, john dad"

您可以使用以下内容来概括这一点。它需要一个主题、一个模式和 1 个或多个替换词。

function replace_each($subject, $pattern, $replacement) {

  $count = 0;
  for ($i = 2; $i < func_num_args(); ++$i) {
    $replacement = func_get_arg($i);
    $subject = preg_replace($pattern, $replacement, $subject, 1, $count);
    if (!$count)
      // no more matches
      break;
  }
  return $subject;
}

$string = preg_replace_each("Hi mom, hi dad", "/hi/i", "mary", "john");

echo $string; // "mary mom, john dad"

【讨论】:

    【解决方案3】:

    preg_replace_callback 是一种方式,另一种是利用 preg_replace 的 $limit 和 $count 参数(见manpage

    $str = "hi foo hi bar hi baz hi quux";
    $repl = array('uno', 'dos', 'tres');
    
    do{
        $str = preg_replace('~hi~', $repl[0], $str, 1, $count);
        $repl[] = array_shift($repl); // rotate the array
    } while($count > 0);    
    

    【讨论】:

      【解决方案4】:

      我不确定是否有一种非常简单的方法可以做到这一点,但请看一下我刚刚编写的这段代码。这应该为您解决问题:)

      <?php
      class myReplace{
          public $replacements = array();
          protected $counter = 0;
      
          public function __construct($replacements) {
            // fill the array with replacements
            $this->replacements = $replacements;
          }
      
          public function test($matches) {
            // if you want you could do something funky to the matches array here
      
            // if the key does not exists we are gonna start from the first 
            // array element again.
            if(!array_key_exists($this->counter, $this->replacements)) {
              $this->counter = 0;
            }
      
            // this will return your replacement.
            return $this->replacements[$this->counter++];
          }
      }
      
      // Instantiate your class here, and insert all your replacements in sequence
      $obj = new myReplace(array('a', 'b'));
      
      // Lets start the replacement :)
      echo preg_replace_callback(
          "/hi/i",
          array($obj, 'test'),
          "Hi mom, hi dad, hi son, hi someone"        
      );
      ?>
      

      此代码将导致: 一个妈妈,一个爸爸,一个儿子,一个人

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-17
        • 1970-01-01
        • 2011-03-26
        • 2020-09-01
        • 2021-07-22
        • 1970-01-01
        相关资源
        最近更新 更多