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
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?

Link to comment
Share on other sites

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'

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.