I have data in this format coming from a database...
BUS 101S Business and Society
or
BUS 101 Business and Society
Notice the optional "S" character (which can be any uppercase character)
I need to replace the "BUS 101S" part with null and here is what I have come up with...
$value = "BUS 101S Business and Society";
$sub = substr($value, 0, 3); // Gives me "BUS"
$num = substr($value, 4, 3); // Gives me "101"
$new_value = preg_replace("/$sub $num"."[A-Z]?/", null, $value);
The value of $new_value
now contains S Business and Society
. So I'm close, Just need it to replace the optional single uppercase character as well. Any ideas?
Assuming the pattern is 3 uppercase letters, 3 numbers and then an optional uppercase letter, just use a single preg_match
:
$new = preg_replace('/^[A-Z]{3} \d{3}[A-Z]?/', '', $old);
The ^
will only match at the beginning of a line/string. The {3}
means "match the preceding token 3 times exactly". The ?
means "match the preceding token zero or one times"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With