PHP在字符串中查找美国州代码


PHP find US state code in string

我有如下格式的字符串:

"Houston, TX" - str1
"Chicago, IL" - str2
"Seattle, WA" - str3

我想提取"TX","IL","WA"当给定上述str1/str2/str3, 如果一个状态码存在于字符串(即2个大写字母在字符串的末尾)使用PHP &regex . .任何指针。我无法可靠地从给定给我的方法的所有字符串中提取此信息。

试试/, [A-Z]{2}$/(去掉逗号,如果不重要)

使用说明:

$stateCode=trim(end(array_filter(explode(',',$string))));
substr($string, -2); // returns the last 2 characters

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

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