根据模式检查字符串 [英] Checking a string against a pattern

查看:80
本文介绍了根据模式检查字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据某种模式检查发布的内容.我在设置此preg_match(或数组?)时遇到麻烦.模式是...

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

并且仍然与图案匹配.

我希望它仍然可以工作,通过去除多余的换行符和/或多余的空白...

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
}

推荐答案

尝试如下操作:

$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);
}

输出:

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

如果与上述条件匹配,则用单个换行符替换2个或多个连续的空白字符\s{2,}.

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

当然,您可能需要将[A-Z]+调整为其他内容.

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

这篇关于根据模式检查字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆