简体   繁体   English

用于获取字符串部分的正则表达

[英]Regular expression for getting string part

I have some string like 我有一些字符串

Shp 1,737 Plenty Rd, Mill Park VIC 3082
560 High St, Preston VIC 3072
217 Mickleham Rd, Tullamarine VIC 3043

from these i need "VIC" . 从这些我需要“VIC”。 Can anyone help me to find out a solution using regex or php string function 任何人都可以帮我找到使用正则表达式或PHP字符串函数的解决方案 在此输入图像描述

This is the actual strings... that read from an excel sheet i want the states name from these string like, NSW, ACT, VIC etc 这是从excel表中读取的实际字符串...我希望这些字符串的状态名称,如NSW,ACT,VIC

如果它始终是倒数第二个,只需将空格上的字符串拆分并取倒数第二个元素。

preg_match_all('/(?P<state>[A-Z]{2,3})\s\d{4}$/m', $str, $matches);

var_dump($matches['state']);

Output 产量

array(3) {
    [0]=>
    string(3) "VIC"
    [1]=>
    string(3) "VIC"
    [2]=>
    string(3) "VIC"
}

This uses a regex in multiline mode to match the 2 or 3 capital letters preceding a whitespace character and a 4 digit postcode. 这在多行模式下使用正则表达式来匹配空白字符和4位数邮政编码之前的2或3个大写字母。

I called it state because I live in Australia and these are all Australian states :) 我称之为state因为我住在澳大利亚,这些都是澳大利亚各州:)

To get vic with its value: 为了获得它的价值:

$getvic = substr($myString,-8,-7);

To get just VIC: 要获得VIC:

$getvic = substr($myString,-8,-2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM