Find term and capture text immediately or after space

0

I have some payment logs and these are the defaults they created the file:

Pattern 1

Apelido
                          -- isso é um espaço
Fulano de Tal

Pattern 2

Apelido:
Fulano de Tal

Pattern 3

Apelido: Fulano de Tal

How can I get all the texts, which in the example would be the nickname "So-and-so", always on the next line after the searched term and ignore lines that have spaces?     

asked by anonymous 10.06.2017 / 07:19

2 answers

1

Basically using preg_replace function.

ideone - the result of your first example

ideone - the result of your second example

ideone - the result of your third example

//1- retira os termos indesejados Apelido e :
$patterns = array();
$patterns[0] = '/Apelido/';
$patterns[1] = '/:/';
$replacements = array();
$replacements[1] = '';
$replacements[0] = '';
$str = preg_replace($patterns, $replacements, $str);

//2- substitui quebras de linha (\n), "retornos de carro" (\r) ou tabulações (\t), por um espaço
$str = preg_replace('/[\n\r\t]/', ' ', $str);

//3- remove qualquer espaço em branco duplicado
$str = preg_replace('/\s(?=\s)/', '', $str);

//Retira espaço no ínicio e final
$str = trim($str);

expressions 2 and 3 can be replaced by a single expression

$str = preg_replace(array('/\s{2,}/', '/[\n\r\t]/',), array(" ", " "), $str);

example - ideone

Or by joining 1, 2, and 3

$str = preg_replace(array('/Apelido/', '/:/', '/\s{2,}/', '/[\n\r\t]/',), array("",""," ", " "), $str);

example - ideone

  

The preg_replace function of php is a substitution function such as str_replace but with some differences, it supports regular expressions and other more powerful features. Preg_replace can be used to make substitutions or even to add characters from specific positions in a given text.

    
10.06.2017 / 09:29
1

I think it's simpler to use the preg_match function, even because the goal is to get a snippet of text and not replace it. Semantic code.

if (preg_match("/(Apelido\:?)(\s+)(.*)/", $test, $matches)) {

    echo $matches[3], PHP_EOL;

}

First, we search for the Apelido[:] pattern, the : character being optional, storing this value in group 1. Second, we look for whitespace, be it white space itself, tabs or breaks line, saving this value in group 2. Third, you search for any content, saving the value in group 3. As you need the nickname value, simply access the value of group 3, as done in echo .

See a test:

$tests = [
    "Apelido\n\nFulano de Tal",
    "Apelido:\nFulano de Tal",
    "Apelido: Fulano de Tal"
];

foreach($tests as $test) {

    if (preg_match("/(Apelido\:?)(\s+)(.*)/", $test, $matches)) {

        echo $matches[3], PHP_EOL;

    }

}

The output will be:

Fulano de Tal
Fulano de Tal
Fulano de Tal
  

See working at Ideone .

    
12.06.2017 / 18:12