根据模式检查字符串

编程入门 行业动态 更新时间:2024-10-11 01:12:29
本文介绍了根据模式检查字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想根据某种模式检查发布的内容.我在设置此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.

更多推荐

根据模式检查字符串

本文发布于:2023-11-12 13:30:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581636.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   模式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!