从一串随机字母中提取子字符串

时间:2015-08-18 09:31:31

标签: php string

我的字符串在自然示例'CBLBTTCCBB'中是随机的。我的目标是计算字符串CTLBT中字符串CBLBTTCCBB的出现次数。不允许重复用于检查的字母。例如,一旦形成CTLBT,下一次迭代的剩余随机字母将为BCCB

场景是我们有刮刮卡,用户可以在其中赢取字母以形成单词CTLBT。根据用户的记录,他赢得的字母是一个字符串CBLBTTCCBB,根据购买的刮刮卡从左到右排序。

我想过使用strpos但似乎不合适,因为它使用了较大字符串中子字符串的确切排列。

关于如何解决这个问题的任何想法?

谢谢!

注意: 问题不是How to count the number of occurrences of a substring in a string?的重复,因为在给定链接中发布的解决方案是不同的。 substr_count计算字符串中子字符串的出现次数,该字符串假定字符串的顺序正确,将形成子字符串。

2 个答案:

答案 0 :(得分:2)

然后可能然后strpos你可以使用preg_replace:

function rand_substr_count($haystack, $needle)
{
    $result = $haystack;

    for($i=0; $i<strlen($needle); $i++) {
        $result = preg_replace('/'.$needle[$i].'/', '', $result, 1);
    }

    if (strlen($haystack) - strlen($result) == strlen($needle)) {
        return 1 + rand_substr_count($result, $needle);
    } else {
        return 0;
    }
}

echo rand_substr_count("CBLBTTCCBB", "CTLBT");

答案 1 :(得分:1)

如果我理解正确,我会这样做(用于显示结果的打印件):

<?
# The string to test
$string="CBLBTTCCBBTLTCC";
# The winning word
$word="CTLBT";

# Get the letters from the word to use them as unique array keys
$letters=array_unique(str_split($word));
print("Letters needed are:\n".print_r($letters,1)."\n");

# Initialize the work array
$match=array("count" => array(),"length"=> array());
# Iterate over the keys to build the array with the number of time the letter is occuring
foreach ($letters as $letter) {
  $match['length'][$letter] = substr_count($word,$letter); #Number of time this letter appears in the winning word
  $match['count'][$letter] = floor(substr_count($string,$letter) / $match['length'][$letter]); # count the letter (will be 0 if none present) and divide by the number of time it should appear, floor it so we have integer

}
print("Count of each letter divided by their appearance times:\n".print_r($match['count'],1)."\n");

# Get the minimum of all letter to know the number of times we can make the winning word
$wins = min($match['count']);
# And print the result
print("Wins: $wins\n");
?>

输出:

Letters needed are:
Array
(
    [0] => C
    [1] => T
    [2] => L
    [3] => B
)

Count of each letter divided by their appearance times:
Array
(
    [C] => 5
    [T] => 2
    [L] => 2
    [B] => 4
)

Wins: 2

由于您希望无论订单如何计算组合,最小字母数将是用户获胜的次数,如果一个字母不存在,则为0。

我让你把它转换成一个函数并清理你不希望的打印行;)