How to use regular expressions to get part of a string?

Solution 1:


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 regex runs in multiline mode (/m) and captures:

(?P[A-Z]{2,3}) → a named group state containing 2–3 uppercase letters

\s → a whitespace character

\d{4}$ → exactly 4 digits at the end of a line

I used the group name state because in my case, these codes represent Australian states.

Solution 2:

If you want to extract “VIC” (with or without spacing) from the string, you can use substr:


// Get " VIC" (with leading space)
$getvic = substr($myString, -8, -7);

// Get "VIC" only
$getvic = substr($myString, -8, -2);

echo $getvic;

This works by taking a slice from the end of the string using negative offsets.