Preg_replace_callback put text before the number

1

I have text that goes like this: Id - Name: Age - Phone

500 - Antonio: Age: 35 years - phone 3681-08xx
Preferences: cycling, traveling.
1,500 - Rodrigo: Age: 20 years - phone 3685-40xx
Preferences: Play dance, read book.

I would like to put in the sentences beginning with numbers the information "Id:", to look like this:

ID: 500 - Antonio: Age: 35 years - phone 3681-08xx
Preferences: cycling, traveling.
ID: 1,500 - Rodrigo: Age: 20 years - phone 3685-40xx
Preferences: Play dance, read book.

How do I do this with preg_replace_callback?

    
asked by anonymous 30.04.2018 / 18:36

2 answers

3

Workaround

  

The conversion of string to integer depends on the format of the string, so PHP evaluates the format of the string and if it does not have any numerical value it will be converted to 0 (zero). If you have numeric value in its first position the value will be considered and if the value is not in the first position it will be disregarded. So we can take advantage of this conditional conversion:

$string  = '500 - Antonio: Idade: 35 anos - telefone 3681-08xx
Preferências: andar de bicicleta, viajar.';

if ((int)($string)) { 
   $string  = "Id: " .$string;
}

echo $string ;

See working at ideone

    
30.04.2018 / 19:22
1

Another possible solution using regex:

$linha = '500 - Antonio: Idade: 35 anos';
$novaLinha = preg_match('#^\d#', $linha) ?
             sprintf('Id: %s', $linha) :
             $linha;

echo $novaLinha . PHP_EOL;
// Id: 500 - Antonio: Idade: 35 anos

Regex:

^\d - string iniciada com dígitos

example - ideone

    
30.04.2018 / 19:34