简体   繁体   English

php preg_match_all在...和之间

[英]php preg_match_all between … and

I'm trying to use preg_match_all to match anything between ... and ... and the line does word wrap. 我正在尝试使用preg_match_all来匹配......之间的任何内容,并且该行会自动换行。 I've done number of searches on google and tried different combinations and nothing is working. 我已经完成了在Google上的搜索次数,并尝试了不同的组合,但没有任何效果。 I have tried this 我已经试过了

preg_match_all('/...(.*).../m/', $rawdata, $m);

Below is an example of what the format will look like: 下面是格式的示例:

...this is a test...

...this is a test this is a test this is a test this is a test this is a test this is a test this is a test this is a test this is a test...

The s modifier allows for . s修饰符允许. to include new line characters so try: 包含换行符,请尝试:

preg_match_all('/\.{3}(.*?)\.{3}/s', $rawdata, $m);

The m modifier you were using is so the ^$ acts on a per line basis rather than per string (since you don't have ^$ doesn't make sense). 您使用的m修饰符是^$基于行而不是基于字符串的行为(因为您没有^$没有意义)。

You can read more about the modifiers here . 您可以在此处阅读有关修饰符的更多信息。

Note the . 注意. needs to be escaped as well because it is a special character meaning any character . 还需要转义,因为它是一个特殊字符,表示any character The ? ? after the .* makes it non-greedy so it will match the first ... that is found. .*使其非贪婪之后,因此它将与找到的第一个...相匹配。 The {3} says three of the previous character. {3}说出前一个字符中的三个。

Regex101 demo: https://regex101.com/r/eO6iD1/1 Regex101演示: https ://regex101.com/r/eO6iD1/1

Please escape the literal dots, since the character is also a regular expressions reservered sign, as you use it inside your code yourself: 请转义文字点,因为字符也是您自己在代码中使用的正则表达式保留符号:

preg_match_all('/\.\.\.(.*)\.\.\./m/', $rawdata, $m)

In case what you wanted to state is that there are line breaks within the content to match you would have to add this explicitely to your code: 如果您要声明的是内容中存在换行符以匹配,则必须将其明确添加到代码中:

preg_match_all('/\.\.\.([.\n\r]*)\.\.\./m/', $rawdata, $m)

Check here for reference on what characters the dot includes: http://www.regular-expressions.info/dot.html 在此处检查有关点包含哪些字符的参考: http : //www.regular-expressions.info/dot.html

You're almost near to get it, 您快要拿到它了,

so you need to update your RE 所以你需要更新你的RE

/\.{3}(.*)\.{3}/m

RE breakdown RE分解

/ : start/end of string / :字符串的开始/结束

\\. : match . :匹配.

{3} : match exactly 3(in this case match exactly 3 dots) {3} :精确匹配3(在这种情况下,精确匹配3个点)

(.*) : match anything that comes after the first match( ... ) (.*) :匹配第一个匹配项之后的任何内容( ...

m : match strings that are over Multi lines. m :匹配多行上的字符串。

and when you're putting all things together, you'll have this 当您将所有东西放在一起时,您将拥有

$str = "...this is a test...";
preg_match_all('/\.{3}(.*)\.{3}/m', $str, $m);
print_r($m);

outputs 输出

Array
(
    [0] => Array
        (
            [0] => ...this is a test...
        )

    [1] => Array
        (
            [0] => this is a test
        )

)

DEMO 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM