2016-01-11 72 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; 
} 

感謝

相關問題