Filter word in a text with php

Question:

I would like to extract some words in a text with php. But they are not fixed words.. I want words that will always change but they will be next to standard keywords EX:

ID: 123123 Name: Elvis Address: Totis bla

I want to filter the values ​​of "ID" "Name" "Address". There is no default separator ID:123, Name: Elvis, Address! It separates by space, by dash, and there you go… Because the text comes from a text extracted from a PDF file and saved in a variable ID: 123, Name: Elvis – Address: toest.

Answer:

Try like this:

$string = "ID : 123123 Nome : Elvis Costelo da silva Endereço : Totis bla florianópolis";

$id = preg_split('#(?<!\\\)ID :|Nome :|Endereço :#', $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);

$id = array_map('trim', $id); //Adicionado para eliminar os espaços

var_dump($id);

Print:

array (size=3)
   0 => string '123123' (length=6)
   1 => string 'Elvis Costelo da silva' (length=22)
   2 => string 'Totis bla florianópolis' (length=24)

Update – No regex solution: (With New User Information).

$string = "Advogado ADVOGADO (OAB: 0000 SC) Código da Publicação 309437294 Disponibilização do Jornal 02/04/2014 Publicação do Jornal 03/04/2014";

$indice = array("Advogado", "Código da Publicação", "Disponibilização do Jornal", "Publicação do Jornal");

for ($i = 0; $i < sizeof($indice); $i++) {
    $a = strpos($string, $indice[$i]);
    $a_size = strlen($indice[$i]);
    if (isset($indice[$i + 1])) {
        $b = strpos($string, $indice[$i + 1]);
    } else {
        $b = strlen($string);
    }
    $valores[] = substr($string, $a + $a_size, $b - $a - $a_size);
}
$resultado = array_combine($indice, $valores);
$resultado = array_map('trim', $resultado);
var_dump($resultado);

Result:

array (size=4)
    'Advogado' => string 'ADVOGADO (OAB: 0000 SC)' (length=23)
    'Código da Publicação' => string '309437294' (length=9)
    'Disponibilização do Jornal' => string '02/04/2014' (length=10)
    'Publicação do Jornal' => string '03/04/2014' (length=10)
Scroll to Top