【问题标题】:Finding string and replacing with same case string查找字符串并用相同的大小写字符串替换
【发布时间】:2011-03-12 00:29:37
【问题描述】:

我在尝试旋转文章时需要帮助。我想查找文本并替换同义文本,同时保持大小写不变。

例如,我有一本像这样的字典:

你好|你好|你好|你好

我需要找到所有hello 并替换为hihowdyhowd'y 中的任何一个。

假设我有一句话:

大家好!当我说你好时,你不应该说你好吗?

在我的手术之后,它会是这样的:

嗨,伙计们!我说你好,你不应该对我说好吗?

在这里,我输掉了这个案子。我要维护它!实际上应该是:

大家好!我说你好,你不应该对我说你好吗?

我的字典大小约为 5000 行

你好|嗨|你好|你好|来吧
薪水|收入|工资
不应该|不应该
...

【问题讨论】:

    标签: php string search replace


    【解决方案1】:

    我建议将preg_replace_callback 与一个回调函数一起使用,该函数检查匹配的单词是否(a)第一个字母不是大写的,或者(b)第一个字母是唯一的大写字母,或者(c)第一个字母不是唯一的大写字母,然后根据需要替换为适当修改的替换词。

    【讨论】:

    • 琥珀色,感谢您的回答。我现在也相信我需要将 preg_replace 与回调一起使用。我的 str_ireplace 将立即替换该单词的所有实例!所以我不能保持不同单词的正确大小写!但是您建议的 3 个条件早在我的脑海中就有:)。但是,由于我没有考虑回调函数,所以我的解决方案不起作用。所以你得到学分:)。
    【解决方案2】:

    你可以找到你的字符串并做两个测试:

    $outputString = 'hi';
    if ( $foundString == ucfirst($foundString) ) {
       $outputString = ucfirst($outputString);
    } else if ( $foundString == strtoupper($foundString) ) {
       $outputString = strtoupper($outputString);
    } else {
       // do not modify string's case
    }
    

    【讨论】:

    • 是的,这就是我打算做的。但可能会有所不同! :)。但是,您的意见肯定会有所帮助。非常感谢您的宝贵时间!
    【解决方案3】:

    这是保留大小写(大写、小写或大写)的解决方案:

    // Assumes $replace is already lowercase
    function convertCase($find, $replace) {
      if (ctype_upper($find) === true)
        return strtoupper($replace);
      else if (ctype_upper($find[0]) === true)
        return ucfirst($replace);
      else
        return $replace;
    }
    
    $find = 'hello';
    $replace = 'hi';
    
    // Find the word in all cases that it occurs in
    while (($pos = stripos($input, $find)) !== false) {
      // Extract the word in its current case
      $found = substr($input, $pos, strlen($find));
    
      // Replace all occurrences of this case
      $input = str_replace($found, convertCase($found, $replace), $input);
    }
    

    【讨论】:

      【解决方案4】:

      您可以尝试以下功能。请注意,它仅适用于 ASCII 字符串,因为它使用了一些有用的 properties of ASCII upper and lower case letters。但是,它应该非常快:

      function preserve_case($old, $new) {
          $mask = strtoupper($old) ^ $old;
          return strtoupper($new) | $mask .
              str_repeat(substr($mask, -1), strlen($new) - strlen($old) );
      }
      
      echo preserve_case('Upper', 'lowercase');
      // Lowercase
      
      echo preserve_case('HELLO', 'howdy');
      // HOWDY
      
      echo preserve_case('lower case', 'UPPER CASE');
      // upper case
      
      echo preserve_case('HELLO', "howd'y");
      // HOWD'Y
      

      这是我的聪明的小 perl 函数的 PHP 版本:

      How do I substitute case insensitively on the LHS while preserving case on the RHS?

      【讨论】:

      • 非常感谢您的意见!
      • 我想我可以使用它!我的主题只有ASCII!所以不会有问题!
      猜你喜欢
      • 1970-01-01
      • 2016-12-11
      • 2020-08-31
      • 1970-01-01
      • 2011-07-08
      • 1970-01-01
      • 2016-01-23
      • 2015-04-22
      • 2019-07-13
      相关资源
      最近更新 更多