Search code examples
phpsplitlimitexplodetext-parsing

Explode string on second last and last space to create exactly 3 elements


I want to split a space-delimited string by its spaces, but I need the total elements in the result array to be exactly 3 AND if the string has more than two spaces, only the last two spaces should be used as delimiters.

My input strings follow a predictable format. The strings are one or more words, then a word, then a parenthetically wrapped word (word in this context is a substring with no whitespaces in it).

Sample strings:

  1. Stack Over Flow Abcpqr (UR)
    becomes:
    ["Stack Over Flow", "Abcpqr", "(UR)"]
  2. Fluency in English Conversation Defklmno (1WIR)
    becomes:
    ["Fluency in English Conversation","Defklmno","(1WIR)"]
  3. English Proficiency GHI (2WIR)
    becomes:
    ["English Proficiency","GHI","(2WIR)"]
  4. Testing ADG (3WIR)
    becomes:
    ["Testing","ADG","(3WIR)"]

I used the following code, but it is only good for Testing (3WIR).

$Original = $row['fld_example'];                                    
$OriginalExplode = explode(' ', $Original);

<input name="example0" id="example0" value="<?php echo $OriginalExplode[0]; ?>" type="text" autocomplete="off" required>

<input name="example1" id="example1" value="<?php echo $OriginalExplode[1]; ?>" type="text" autocomplete="off" required>

Basically, I just need to explode the string on spaces, starting from the end of the string, and limiting the total explosions to 2 (to make 3 elements.


Solution

  • You can approach this using explode and str_replace

    $string = "Testing (3WIR)";
    $stringToArray = explode(":",str_replace("(",":(",$string));
    echo '<pre>';
    print_r($stringToArray);
    

    Edited question answer:-

    $subject = "Fluency in English Conversation Defklmno (1WIR)";
    $toArray = explode(' ',$subject);
    if(count($toArray) > 2){
      $first       = implode(" ",array_slice($toArray, 0,count($toArray)-2));
      $second      = $toArray[count($toArray)-2];
      $third       = $toArray[count($toArray)-1];
      $result      = array_values(array_filter([$first, $second, $third]));
    }else{
      $result = array_values(array_filter(explode(":",str_replace("(",":(",$subject))));
    }
    

    DEMO HERE