views:

74

answers:

3

I want to check posted content against a pattern. I am having trouble setting up this preg_match (or array?). The pattern being...

TEXTHERE:TEXTHERE
TEST:TEST
FILE:FILE

AND

TEXTHERE:TEXTHERE TEST:TEST FILE:FILE

I want to check for either pattern, the one with the whitespace and the one with the line break. If the posted content is this... (with extra line breaks and/or whitespace)

TEXTHERE:TEXTHERE

TEST:TEST

FILE:FILE

I want it to somehow display as...

TEXTHERE:TEXTHERE
TEST:TEST
FILE:FILE

and still match against the pattern.

I want it to still work, somehow by stripping the extra line break/and or extra white space...

$loader = file_get_contents( 'temp/load-'.$list.'.php' );

If it doesn't follow the string pattern, I want it to output an error message, etc.

if($loader == ???) { // done
} else { // error
}
+1  A: 
   preg_match('~^\s*(\S+:\S+(\s+|$))+$~', $str)

this matches "AA:BB CC:DD" or "AA:BB \n CC:DD" and fails on "AA:BB foo CC:DD"

stereofrog
+1  A: 

Try something like this:

$loader = 'TEXTHERE:TEXTHERE

TEST:TEST

FILE:FILE';

if(preg_match('/^[A-Z]+:[A-Z]+(\s+[A-Z]+:[A-Z]+)*$/', $loader)) {
    echo preg_replace('/\s{2,}/', "\n", $loader);
}

Output:

TEXTHERE:TEXTHERE 
TEST:TEST
FILE:FILE

You'll get the same output for:

$loader = 'TEXTHERE:TEXTHERE        TEST:TEST          FILE:FILE';

You first check if it matches:

[A-Z]+:[A-Z]+    # match a word followed by a colon followed by a word
(                # open group 1
  \s+            #   match one or more white space chars (includes line breaks!)
  [A-Z]+:[A-Z]+  #   match a word followed by a colon followed by a word
)*               # close group 1 and repeat it zero or more times

And if it matches the above, you replace 2 or more successive white space chars \s{2,} with a single line break.

Of course, you may need to adjust [A-Z]+ to something else.

Bart Kiers
Thanks for the explanation.
Homework
You're welcome Joey.
Bart Kiers
@Bart, this accepts test:test:test, can I limit it to only accept test:test test:test and not test:test:test:test, etc?
Homework
Anchor the regex with `^` and `$`, the start and end of the input string respectively. (see the edit)
Bart Kiers
A: 
if(preg_match_all('/([A-Za-z0-9-_\.:]+)[\n\s]*/', $subject, $matches)){
  print $matches[0][0]."<br />".$matches[0][1]."<br />".$matches[0][2];
}else{
  // error
}
Brandon G