Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional Character in PHP Regular Expression Replace

Tags:

regex

php

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?

like image 422
Alex_Hyzer_Kenoyer Avatar asked Dec 22 '22 00:12

Alex_Hyzer_Kenoyer


1 Answers

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"

like image 149
Cal Avatar answered Dec 24 '22 01:12

Cal