Paste text between two words with regex

3

I would like a light for my problem. My goal is to get the list below by dividing the blocks between the words LOREM and LOREM but I do not want to get the whole text that follows the end of the list pattern, as follows:

LOREM : 10505050
IPSUM : 1050051051084
DOLOR : 2620620620652
AMETI : 54084840540540
LOREM : 10505050
IPSUM : 1050051051084
DOLOR : 2620620620652
AMETI : 54084840540540
LOREM : 10505050
IPSUM : 1050051051084
DOLOR : 2620620620652
AMETI : 54084840540540
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

I'm using this regex: /(?=LOREM :).+?(?:(?=LOREM :))/s I am able to select all but the last block of text I can not select.

To better understand this example: link

    
asked by anonymous 10.12.2014 / 18:56

2 answers

1

I suggest two approaches:

# 1: By steps

You could split this text in the "interesting part" and throw away the rest using for example ([^\.]+[\d]+) .

Then I would just stick with the chave : valor pattern and could do a simpler match that would give an array with each line. Something like this :

$regex = '(([\w]+) : ([\d]+))';
preg_match_all($regex, $string, $matches);

# 2: Regex Grouping Capture

You could have a regex that directly captures groups, which means that your group pattern is consistent. A suggestion is to do so :

$regex = '(([\w]+ : [\d]+[\s\n\r]){4})';
preg_match_all($regex, $string, $matches);
    
11.12.2014 / 00:25
0

1 - Use strlen

It returns the length of a text passed as an argument. Example of using the function strlen:

<?php
    /*string strlen (string entrada)*/
    $qtd_char = strlen("Linha");
    echo $qtd_char;
?>

** The displayed value will be "6" because the text "Code Line" contains six characters. *

2nd With the amount of text purchased use Substr .

The substr is responsible for returning a piece of string. For this it uses three parameters: the string itself, the initial index and the amount of characters to return.

It turns out that we can also use a negative index, so PHP parses the string by counting N characters from the end, not from the beginning. Here are some examples:

<?php

$texto = "eu não sou besta pra tirar onda de herói";

echo substr($texto, 0, $qtd_char);  // eu não sou besta

?>

We can also use substr () in combination with strpos (). Strpos detects the position that a string occurs within an expression.

    
10.12.2014 / 19:09