Preg_replace_callback put text before number

Asked

Viewed 38 times

0

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

500 - Antonio: Age: 35 years - phone 3681-08xx
Preferences: ride a bike, travel.
1,500 - Rodrigo: Age: 20 years - phone 3685-40xx
Preferences: Play dance, read book.

I would like to put in the phrases that start with numbers the information "Id: ", to look like this:

ID: 500 - Antonio: Age: 35 years - phone 3681-08xx
Preferences: ride a bike, travel.
ID: 1.500 - Rodrigo: Age: 20 years - phone 3685-40xx
Preferences: Play dance, read book.

How do I do this with preg_replace_callback?

  • And how that phrase is put together?

  • is a plain text, no markup, would like to search the whole text, and where to contain a sentence starting with number insert the text "ID : "

  • 1

    Wouldn’t that help? http://sandbox.onlinephpfunctions.com/code/ba45ef3ae5b0d84238fcc58665d20385c1c9f5e2

  • Served as a glove, thank you very much man

  • I’ll put as an answer and add an explanation

2 answers

3


Workaround

The conversion from string to integer depends on the format of the string, so PHP evaluates the format of the string and if it has no numerical value it will be converted to 0(zero). If you have numeric value in your first position the value will be considered and if the value is not in the first position will be disregarded. Therefore we can avail this conversion in the conditional:

$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 on ideone

  • 2

    He aimed at the armadillo, he hit the caititu! D

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.