1

我有以下可能的字符串:

NL DE 
NL,DE
nl DE
nl de
NL/DE
NL,mismatch,DE

我正在寻找在preg_match给定上述输入的情况下产生以下输出的那个。

array(
  [0]=>"NL",
  [1]=>"DE"
);

我试过以下代码:

preg_match_all('/(\w{2,2})/ui', $info["country"], $m);

但这似乎也切断了这个词mismatch,这是不受欢迎的。

正则表达式应该只匹配两个字母的国家代码,其他的都应该被忽略。

如何preg_match在 PHP 中使用?

4

3 回答 3

4

下面是你如何分解字符串:

$string = 'NL DE 
NL,DE
nl DE
nl de
NL/DE
NL,mismatch,DE';

使用explodefilter

$string = explode("\n",str_replace(array(",","/"," ","\r"), "\n", strtoupper($string)));
$string = array_unique(array_filter($string,function($v){$v = trim($v); return strlen($v) === 2;}));
var_dump($string);

如果你想玩这个字符串,试试这个:

$s = ",\n\t \r";
$t = strtok(strtoupper($string), $s);
$l = array();
while ( $t !== false ) {
    in_array($t, $l) OR strlen($t) == 2 AND $l[] = $t AND $t = strtok($s);
}
var_dump($l);

输出:

array
  0 => string 'NL' (length=2)
  1 => string 'DE' (length=2)
于 2012-10-19T15:48:34.957 回答
3
// @claudrian Variant
function SplitCountries($string){
    // Sanity check
    if(!is_string($string)) return false;
    // Split string by non-letters (case insensitive)
    $slices = preg_split('~[^a-z]+~i', trim($string));
    // Keep only 2-letter words
    $slices = preg_grep('~^[a-z]{2}$~i', $slices);
    // Keep uniques
    $slices = array_unique($slices);
    // Done
    return $slices;
}

// @Wiseguy Variant
function SplitCountries($string){
    // Sanity check
    if(!is_string($string)) return false;
    // Capture only two letter packs
    if(!preg_match_all('~\\b[a-z]{2}\\b~i', trim($string), $slices)){
        return false;
    }
    // Keep uniques
    $slices = array_unique($slices[0]);
    // Done
    return $slices;
}

希望能帮助到你。

于 2012-10-19T15:46:12.620 回答
1

这应该工作

$result = array();
preg_match_all('/([a-z]{2})(?:.*)?([a-z]{2})/i',$text, $matches);
$result = array( strtolower( $matches[1][0] ), strtolower( $matches[2][0] ) );

您将在 $result 数组中获得结果

于 2012-10-19T15:49:55.123 回答