Check if the line begins with certain words, and split it if it

$str = 'foooo'; // <- true; how can I get 'foo' + 'oo' ?
$words = array(  
  'foo',
  'oo'
);

What is the fastest way to find out if it starts $strwith one of the words from the array and splits it if it does?

+3
source share
4 answers

Using $wordsand $strin your example:

$pieces = preg_split('/^('.implode('|', $words).')/', 
             $str, 0, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

Result:

array(2) {
  [0]=>
  string(3) "foo"
  [1]=>
  string(2) "oo"
}
+5
source

Try:

<?php
function helper($str, $words) {
    foreach ($words as $word) {
        if (substr($str, 0, strlen($word)) == $word) {
            return array(
                $word,
                substr($str, strlen($word))
            );
        }
    }

    return null;
}

$words = array(  
  'foo',
  'moo',
  'whatever',
);

$str = 'foooo';

print_r(helper($str, $words));

Output

Array
(
    [0] => foo
    [1] => oo
)
+3
source

This solution iterates through the array $wordsand checks to see if it starts $strwith any words in it. If he finds a match, he reduces $strto $wand breaks.

foreach ($words as $w) {
     if ($w == substr($str, 0, strlen($w))) {
          $str=$w;
          break;
     }
}
+2
source
string[] MaybeSplitString(string[] searchArray, string predicate)
{
  foreach(string str in searchArray)
  {
    if(predicate.StartsWith(str)
       return new string[] {str, predicate.Replace(str, "")};
  }
  return predicate;
}

This will require a translation from C # to PHP, but this should point you in the right direction.

+1
source

All Articles