Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/234.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP查找字符串中的状态代码_Php_Regex - Fatal编程技术网

PHP查找字符串中的状态代码

PHP查找字符串中的状态代码,php,regex,Php,Regex,我有如下格式的字符串: “德克萨斯州休斯顿”-str1 “伊利诺伊州芝加哥”-str2 “华盛顿州西雅图”-str3 如果字符串中存在状态代码(即字符串末尾的2个大写字母),我想在给定上述每个str1/str2/str3时提取“TX”、“IL”、“WA”。。任何指针。。我无法从提供给我的方法的所有字符串中可靠地提取此信息。请尝试/,[A-Z]{2}$/(如果不重要,请删除逗号)。使用: $stateCode=trim(end(array_filter(explode(',',$string)))

我有如下格式的字符串:

“德克萨斯州休斯顿”-str1
“伊利诺伊州芝加哥”-str2
“华盛顿州西雅图”-str3


如果字符串中存在状态代码(即字符串末尾的2个大写字母),我想在给定上述每个str1/str2/str3时提取“TX”、“IL”、“WA”。。任何指针。。我无法从提供给我的方法的所有字符串中可靠地提取此信息。

请尝试
/,[A-Z]{2}$/
(如果不重要,请删除逗号)。

使用:

$stateCode=trim(end(array_filter(explode(',',$string))));

您不需要为此使用正则表达式。假设状态代码只能出现在字符串的最末尾,则可以使用以下小函数:

/**
 * Extracts the US state code from a string and returns it, otherwise
 * returns false.
 *
 * "Houston, TX" - returns "TX"
 * "TX, Houston" - returns false
 *
 * @return string|boolean
 */
function getStateCode($string)
{
    // I'm not familiar with all the state codes, you
    // should add them yourself.
    $codes = array('TX', 'IL', 'WA');

    $code = strtoupper(substr($string, -2));

    if(in_array($code, $codes))
    {
        return $code;
    }
    else
    {
        return false;
    }
}

对于正则表达式,请尝试这个方便的工具:或者使用
/,([A-Z]{2})$/
,并获取组而不是整个匹配。
/**
 * Extracts the US state code from a string and returns it, otherwise
 * returns false.
 *
 * "Houston, TX" - returns "TX"
 * "TX, Houston" - returns false
 *
 * @return string|boolean
 */
function getStateCode($string)
{
    // I'm not familiar with all the state codes, you
    // should add them yourself.
    $codes = array('TX', 'IL', 'WA');

    $code = strtoupper(substr($string, -2));

    if(in_array($code, $codes))
    {
        return $code;
    }
    else
    {
        return false;
    }
}