2016-01-11 53 views
-1

我想在字之间添加字符串xx,假设这两个字之间既不存在xx也不存在yy。实例:php - 如何在字符串中的两个单词之间插入单词?

  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之间的两个词,如果有没有其他xx也不另一yy。但是,如果在两个单词的MIDDLE中存在xxyy,请不要添加任何内容。

如何编写此功能?

+8

您是否尝试过的东西来实现自己的目标的答案? – Rizier123

+2

爆炸的空间,循环,有点棘手 –

+0

我试过一些子字符串,但没有什么 – user2580401

回答

-1

编写代码以“## @@ %% xx %% @@ ##”替换“xx”,然后用“xx”替换每个空格,然后将每个“## @@ %% xx %% “@@ ##”和“xx”

通过用稍后可以展开的东西折叠空格,您可以专注于新增加的内容。

然后换YY

+0

为什么投了票?这个答案有效。 –

0

我想出的答案是一样的:

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; 
} 

感谢

相关问题