如何在字符串中的两个单词之间插入一个单词


how to insert a word only between two words in a string?

我想在单词之间添加字符串xx,假设这些单词之间既不存在xx也不存在yy。示例:

  1. this house->this xx house
  2. this xx house->this xx house
  3. this yy house->this yy house
  4. this is my house->this xx is xx my xx house
  5. this yy is my house->this yy is xx my xx house
  6. xx xx->xx xx xx
  7. this is my house yy indeed->this xx is xx my xx house yy indeed

其想法是,如果既没有另一个xx也没有另一yy,则默认情况下在两个单词之间插入单词xx。但是,如果在两个单词的中间存在xxyy,则不添加任何内容。

如何编写此函数?

我想出了一个答案:

function my_function($string){
    $value = "";
    $string = preg_replace('/'s+/', ' ', $string);
    $string = explode(" ", $string);
    for($i = 0; $i < sizeof($string); $i++ ){ //"for loop" here
        if( $i !== (sizeof($string) - 1) ){    //do not count the last element 
            if( strtolower($string[$i + 1]) !== "xx" && strtolower($string[$i + 1]) !== "yy" ){ //if next element is not an "and" then we should add it
                if( strtolower($string[$i]) !== "xx" && strtolower($string[$i]) !== "yy" ){ //if the actual element is not already an "AND"
                    array_splice($string, $i + 1, 0, "xx" );
                    $i = $i + 1;
                }
            }
        }
    }
    foreach ($string as $i){
        $value = $value . $i . " ";
    }
    return $value;
}

感谢您的回答

编写代码,将"xx"替换为"###@@%%xx%%@@##",然后将每个空格替换为"xx",然后用"xx"替换每个"###@@%%xx%%@@###"

通过用以后可以扩展的东西折叠空间,您可以专注于新添加的内容。

然后对yy 执行相同操作