Jump to content

Formatting question with semicolons


barkster

Recommended Posts

I have a string that can be any of the following want to make sure it is formatted correctly where if there is more than one entry they are separated by a semicolon and a space and the last entry does not have a semicolon.  I cannot figure out how to do this, right now I'm just doing this. So essentially it can either be 3digit alpha or 3-digit alpha plus semicolon and space? 

 

Formats Accepted

BBB

BBB; BBB

BBB; BBB; BBB; BBB

 

regex using now ^([A-Za-z; ])*$

Link to comment
https://forums.phpfreaks.com/topic/146875-formatting-question-with-semicolons/
Share on other sites

Based off of Effigy's snippet, perhaps:

 

$tests = array(
	'BBB',
	'BBB; BBB',
	'BBB; BBB; BBB; BBB',
	'B;',
	';B',
	';;',
);

foreach ($tests as $test) {
    echo "$test => ";
    echo preg_match('#\A([a-z0-9]{3}(?:; )?)+\z#i', $test) ? 'OK' . "<br />\n" : 'Not OK' . "<br />\n" ;
}

 

Output:

BBB => OK
BBB; BBB => OK
BBB; BBB; BBB; BBB => OK
B; => Not OK
;B => Not OK
;; => Not OK

 

Is that what you are looking for?

I just realized that if it is only a format you are checking (in other words, you won't need to do any capturing at all), my initial brackets should be converted to non-capturing, much like the optional ;space part...

 

Pattern:

'#\A(?:[a-z0-9]{3}(?:; )?)+\z#i'

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.