J
J
jasonOk2015-12-28 10:39:53
PHP
jasonOk, 2015-12-28 10:39:53

How to replace matches in text?

There is a regular expression, for example, let's take the simplest one and display it in the code , but how can I make the replacement variable change depending on the value that matches pattern ? It turns out that there are the same ones , but when a value suitable for the pattern is found (the first will be ) , a query is made to the database and then, depending on the match, the unit, for example, is replaced by "one", then the match is again a request and we replace it with "two" and so on . How can this be done? /[0-9]/preg_replace("/[0-9]/","num","1 2 3");num num num
1 2 31
2

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
Cat Anton, 2015-12-28
@jasonOk

preg_replace_callback()

$result = preg_replace_callback('/\d/', function ($matches) use ($db) {
    // Запрос к базе данных $db
    return $replace;
}, '1 2 3');

O
Optimus, 2015-12-28
Pyan @marrk2

if(preg_match("/1/ism", $you)){
    // запрос к БД
    if($otvet_bd == 'need'){
        preg_replace("/1/ism", "new", $you)
    }
}

And so on if for each case...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question