开发者

Check if a string starts with certain words, and split it if it is

$str = 'foooo'; // <- true; how can I ge开发者_如何学Got 'foo' + 'oo' ?
$words = array(  
  'foo',
  'oo'
);

What's the fastest way I could find out if $str starts with one of the words from the array, and split it if it does?


Using $words and $str from 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"
}


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
)


This solution iterates through the $words array and checks if $str starts with any words in it. If it finds a match, it reduces $str to $w and breaks.

foreach ($words as $w) {
     if ($w == substr($str, 0, strlen($w))) {
          $str=$w;
          break;
     }
}


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 need translation from C# into PHP, but this should point you in the right direction.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜