【问题标题】:How do i start text str_split after some characters如何在某些字符后开始文本 str_split
【发布时间】:2017-11-01 10:38:03
【问题描述】:

我有代码:

$txt = "lookSTARTfromhereSTARTagainhere";

$disp = str_split($txt, 4); 

for ($b = 0; $b<3; $b++) {
    echo "$disp[$b]"; 
} 

在“lookSTARTfromhereSTARTagainhere”的文本行中返回“look”、“STAR”、“Tfor”我的问题是如何从“START”开始我的文本拆分示例我的结果拆分后“lookSTARTfromhereSTARTagainhere”文本行的输出看起来像“from”“here”“again”感谢您的时间和理解

【问题讨论】:

  • 所以你根本不希望START出现吧?只看,从这里,又想出现在这里
  • @pr1ce3 只是从 START 开始 str_split e:g 'from' 'here' 'again' to apear 仅感谢您对我的解决方案的影响
  • 预期的数组是否应该是["from", "here", "again", "here"]?一个词是五个字母,其他四个。代码如何知道哪个是哪个?
  • @EniediMonday 检查我的答案。如果有帮助的话。
  • @EniediMonday 如果提供的任何解决方案有效。请务必接受。

标签: php string split character


【解决方案1】:

str_split 可能无法实现,因为 'again' 有 5 个字符。您可以通过以下代码获取 'from'、'here'。

$txt = "lookSTARTfromhereSTARTagainhere";
$txt = str_replace('look','',$txt);
$txt = str_replace('START','',$txt);
$disp = str_split($txt, 4); 
for ($b = 0; $b<3; $b++) {
    echo "$disp[$b]"; 
} 

【讨论】:

    【解决方案2】:

    我如何从“START”开始我的文本拆分

    只需使用explodearray_slice 函数:

    $txt = "lookSTARTfromhereSTARTagainhere";
    $result = array_slice(explode('START', $txt), 1);
    
    print_r($result);
    

    输出:

    Array
    (
        [0] => fromhere
        [1] => againhere
    )
    

    【讨论】:

      【解决方案3】:

      如果您的预期输出是从开始时的四个字母单词,您可以在 START 上展开然后删除第一项并使用 str_split 将每个数组项拆分为四个字母单词。

      $txt = "lookSTARTfromhereSTARTagainhere";
      
      $arr = explode("START", $txt); // Explode on START
      unset($arr[0]); // first item is before START, we don't need that.
      $res = [];
      foreach($arr as $val){
          $temp = str_split($val, 4); // Split array item on four letters.
          $res = array_merge($res, $temp); // merge the new array with result array
      }
      var_dump($res);
      

      https://3v4l.org/3BQ1b

      【讨论】:

        【解决方案4】:
        <?php
        
        $txt = "lookSTARTfromhereSTARTagainhere";
        
        $split = explode("START",$txt);
        unset($split[0]);
        
        $first_str = str_split($split[1],4);
        $t2 = str_split($split[2],5);
        
        $second_str = $t2[0];
        
        array_push($first_str,$second_str);
        
        print_r($first_str);
        
        ?>
        

        输出

        数组([0] => 来自 [1] => 此处 [2] => 再次)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-02-07
          • 1970-01-01
          • 1970-01-01
          • 2019-12-21
          • 1970-01-01
          相关资源
          最近更新 更多