如何使一个与爆炸和内爆功能相同的功能

时间:2016-03-08 16:13:43

标签: php function

任何人帮助我如何制作与爆炸和内爆功能相同的功能

2 个答案:

答案 0 :(得分:1)

让我们首先看一下爆炸的内容:(来自php.net)

  

返回一个字符串数组,每个字符串都是字符串的子字符串,通过在字符串分隔符形成的边界上将其拆分而形成。

表示

explode(' ', '1 2 3 4 5 6 7 8'); // will return the array of strings
// array(
//   0 => '1',
//   1 => '2',
//   2 => '3',
//   3 => '4',
//   4 => '5',
//   5 => '6',
//   6 => '7',
//   7 => '8'
// )

在上面的示例中,分隔符是空格,字符串是1 ... 8

同样让我们在伪代码中解决这个问题:

  1. 函数需要2个参数,分隔符和字符串
  2. 创建一个空数组
  3. 查找字符串的长度
  4. 在字符串
  5. 中查找分隔符的第一个位置
  6. 从字符串中取出子字符串,直到分隔符的第一个位置
  7. 将子字符串存储在数组
  8. 重复步骤3-6,直到字符串长度为零。
  9. 返回数组
  10. function letsExplode(String $delimiter, String $string): array  
    {  
      $arr = [];  
      while(strlen($string) > 0)  
      {  
        $pos = strpos($string, $delimiter);  
        if($pos)  
        {  
          $arr[] = trim(substr($string, 0, $pos));  
          $string = ltrim(substr($string, $pos), $delimiter);  
        } else {  
          $arr[] = trim($string);  
          $string = '';  
        }  
      }  
      return $arr;  
    }
    
    letsExplode(' ', '1 2 3 4 5 6 7 8'); or letsExplode(',', '1, 2, 3, 4, 5, 6, 7, 8');
    // array(
    //   0 => '1',
    //   1 => '2',
    //   2 => '3',
    //   3 => '4',
    //   4 => '5',
    //   5 => '6',
    //   6 => '7',
    //   7 => ' 8'
    // )
    

答案 1 :(得分:0)

<?
function my_implode($array, $delimiter){    
    end($array); //Set the internal pointer of an array to its last element
    $end = key($array); // Fetch a key from the array
    $final_string = "";
    foreach ($array as $key => $value) {
        $final_string .= $value; // adds to the string.
        if($key != $end) $final_string .= $delimiter; //If not end of array adds the delimiter to the string
    }

    return $final_string;
}

function my_explode($string, $delimiter){    
    $array = preg_split("/".$delimiter."/", $string);
    return $array;
}

// test explode/implode:

$string = "this is string djhf sjs jkdfh skjfjdsf hkdsjfh kjsd fhks";
$delimiter = " ";
$array = my_explode($string, $delimiter);

echo "<br>Test Explode, <br><b>String:</b> ".$string."<br><br>";
echo "<b>Result:</b><br>";
echo "<pre>";
print_r($array);
echo "</pre>";

echo "<br><br><br>";

echo "<br>Test Implode:<br><br>";
$string_final = my_implode($array, " ") ;
echo "Result:<br>". $string_final;
echo "<br><br><br>";
if ($string == $string_final) {

    echo "<b>Test Successful.</b> <br> <br>Original String: <br>".$string. "<br>Final String:<br>". $string_final;
    echo "<b><br>String are identical</b>";
} else {
    Echo "<b>Test Failed!</b> <br><br>Original String:<br>".$string. "<br>Final String:<br>". $string_final;
}