簡體   English   中英

檢查字符串是否以某些單詞開頭,如果是則將其拆分

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

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

我可以找出$str是否以數組中的一個單詞開頭並拆分它的最快方法是什么?

使用示例中的$words$str

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

結果:

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

嘗試:

<?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
)

此解決方案遍歷$words數組並檢查$str是否以其中的任何單詞開頭。 如果找到匹配項,它會將$str減少到$w並中斷。

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;
}

這需要從 C# 轉換為 PHP,但這應該為您指明正確的方向。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM