我想在单词之间添加字符串xx
,假设这些单词之间既不存在xx
也不存在yy
。示例:
this house
->this xx house
this xx house
->this xx house
this yy house
->this yy house
this is my house
->this xx is xx my xx house
this yy is my house
->this yy is xx my xx house
xx xx
->xx xx xx
this is my house yy indeed
->this xx is xx my xx house yy indeed
其想法是,如果既没有另一个xx
也没有另一yy
,则默认情况下在两个单词之间插入单词xx
。但是,如果在两个单词的中间存在xx
或yy
,则不添加任何内容。
如何编写此函数?
我想出了一个答案:
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 执行相同操作