2016年10月7日 星期五

PHP找出至少出現N個X

假設一串數字,如何找出是否匹配出現N個 X 數字的方法

ex. 找出一個字串剛好有21個逗號(, commas)的方法

/^([^,]*,){21}[^,]*$/

^Start of string
(Start of group
[^,]*Any character except comma, zero or more times
,A comma
){21}End and repeat the group 21 times
[^,]*Any character except comma, zero or more times again
$End of string

所以找出131353,是否至少出現兩個1
mysql> SELECT '131353' REGEXP "^([^1]*1){2}";
1
是否至少出現一個4
mysql> SELECT '131353' REGEXP "^([^4]*4){1}";
0

找出連續出現N次的X數字

ex. 找出任何字元連續重複超過10次

/(.)\1{9,}/

131353,是否連續出現三個3
$ perl -e 'print "131353" =~ /(3)\1{2,}/;'
(false)
133351,是否連續出現三個3
$ perl -e 'print "133351" =~ /(3)\1{2,}/;'
3 => 匹配

什麼是正則的 \1 ?
Here the \1 is called a backreference. It references what is captured by the dot . between the brackets (.) and then the {9,} asks for nine or more of the same character. Thus this matches ten or more of any single character.
\1 是 反向引用,它引用括號 (.) 內的 . ,然後{9,} 要求9次以上相同的字元,因此這個正則匹配10個以上相同的字元

PHP匹配字串中所有重複的字元
$string = "14433";
preg_match_all('/(.)\1+/', $string, $matches);
$result = array_combine($matches[0], array_map('strlen', $matches[0]));
arsort($result);

$result:Array
(
    [33] => 2
    [44] => 2
)
如果只是要算哪個數字重複了幾次
$string = "14433";
$result = array_count_values(str_split($string));
arsort($result);

$result:Array
(
    [3] => 2
    [4] => 2
    [1] => 1
)

3重複了2次、4重複了2次、1重複了1次

找至少出現兩次以上的
$count = 2;
$filteredArray = array_filter($result, function($a) use($count) { return ($a >= $count);});

$filteredArray:Array
(
    [3] => 2
    [4] => 2
)

這邊array_filter()的callback使用匿名函數(anonymous functions),PHP 5.3.0以上才支援匿名函數寫法
使用 use($count) 將參數傳進匿名函數裡,PHP 5.3以上才支持

將array的key implode()
$filtered_string = implode(", ", array_keys($filteredArray));
$filtered_string = "3, 4"

參考資料:
http://stackoverflow.com/questions/863125/regular-expression-to-count-number-of-commas-in-a-string  Regular expression to count number of commas in a string
http://stackoverflow.com/questions/1660694/regular-expression-to-match-any-character-being-repeated-more-than-10-times  Regular expression to match any character being repeated more than 10 times
http://stackoverflow.com/questions/25773605/determine-repeat-characters-in-a-php-string  Determine repeat characters in a php string
http://stackoverflow.com/questions/1503579/how-to-filter-an-array-by-a-condition/1503595  How to filter an array by a condition
http://stackoverflow.com/questions/3635945/remove-empty-array-elements-with-array-filter-with-a-callback-function  Remove empty array elements with array_filter with a callback function
http://stackoverflow.com/questions/5482989/php-array-filter-with-arguments  PHP array_filter with arguments
http://www.codesynthesis.co.uk/code-snippets/how-to-implode-array-keys-in-php  HOW TO IMPLODE ARRAY KEYS IN PHP








沒有留言:

張貼留言