Checking a string against a pattern

人盡茶涼 提交于 2019-12-25 02:42:50

问题


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:


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.




回答2:


   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"




回答3:


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
}


来源:https://stackoverflow.com/questions/1737091/checking-a-string-against-a-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!