如何在保持大小写的同时在单词中插入字符

问题描述 投票:1回答:2

如果在保持大小写的同时找到单词匹配,我想在字符串中的单词内插入一个字符。这段代码工作正常,但我必须指定结果字。

$string = "Quick brown fOx jumps right over the lazy dog.";
$swears = array(
    "BROWN" => "BRO.WN",
    "fox"  => "f.ox",
    "Dog"  => "D.og",
);
$filtered = str_ireplace(array_keys($swears), array_values($swears), $string);

这段代码的问题是任何“棕色”变成BRO.WN如果单词匹配,是否可以插入一个字符。就像布朗变成兄弟;在保持表壳的同时,棕色变成了兄弟。

php replace
2个回答
2
投票

可能有更好的方法可以做到这一点,但这是我提出的唯一答案:

 foreach($swears as $swear => $modified_swear) {
   $swear_pos = stripos($string, $swear);
   if($swear_pos !== false) {
     $swear_len = strlen($swear);
     if($swear_len >= 3) {
       $new_string = substr($string, 0, $swear_pos);
       $new_string .= substr($string, $swear_pos, $swear_len-2);
       $new_string .= '.';
       $new_string .= substr($string, $swear_pos+($swear_len-2));
       $string = $new_string;
     }
   }
}

此代码仅在您实际尝试在发誓的最后两个字符之前添加单个点时才有效。

编辑:

可以修改所有单词列表的新代码。

    $searched_pattern = '/\b(?:';
foreach($swears as $swear => $modified_swear) {
  $searched_pattern .= '('.$swear.')|';
}
$searched_pattern = rtrim($searched_pattern, '|');
$searched_pattern .= ')\b/i';

$string = preg_replace_callback(
  $searched_pattern,
  function($matches) {
    $word = $matches[0];
    $swear_len = strlen($word);
    if($swear_len >= 3) {
      $new_word .= substr($word, 0, $swear_len-2);
      $new_word .= '.';
      $new_word .= substr($word, $swear_len-2);
      $word = $new_word;
    }
    return $word;
  },
  $string
);

0
投票

我不清楚你想要什么?这个测试有其他选择。然后执行str_replace将char插入特定位置。

   <?php
$string = "Quick brown fOx jumps right over the lazy dog.";
$swears = array(
    "BROWN" => "BRO.WN",
    "fox"  => "f.ox",
    "Dog"  => "D.og"
);
$string_arr = explode(" ",$string);
    $swears_arr = array_keys($swears);
    foreach ($swears as $swear_key => $swear_word) {
    foreach ($string_arr as $key => $word) {
        if (preg_replace('/[^a-z]+/i', '', strtolower($word)) == strtolower($swear_key)) {
             $string_arr[$key] = substr_replace($word, '.', 1, 0);
                                 }
                                            } 
                                                   }

    // put the sentence back together:

    $new_string = implode(" ",$string_arr);
print_r($new_string);
    ?>
© www.soinside.com 2019 - 2024. All rights reserved.