简体   繁体   中英

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. I've done number of searches on google and tried different combinations and nothing is working. 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 . 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).

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 . The ? after the .* makes it non-greedy so it will match the first ... that is found. The {3} says three of the previous character.

Regex101 demo: 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

You're almost near to get it,

so you need to update your RE

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

RE breakdown

/ : start/end of string

\\. : match .

{3} : match exactly 3(in this case match exactly 3 dots)

(.*) : match anything that comes after the first match( ... )

m : match strings that are over Multi lines.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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