Reputation: 5097
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
}
Upvotes: 0
Views: 1559
Reputation: 170258
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.
Upvotes: 1
Reputation: 2893
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
}
Upvotes: 0
Reputation: 53950
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"
Upvotes: 1