A
A
Alexander2016-03-08 10:14:19
Regular Expressions
Alexander, 2016-03-08 10:14:19

How to escape pattern with a variable so that preg_replace works?

Friends, welcome.
Can you please tell me how to properly process the variable for a successful preg_replace?
The $query variable is generated based on the user's request. What the user requested - must be highlighted.
If the code is like this, then the $contt variable returns NULL

$query = "/(\\[jkj|холо)/i";
<?=var_dump(preg_replace("/".$query."/i", "<b>$0</b>", $contt)));

If the code is like this:
$query = "/(\\[jkj|холо)/i";
<?=var_dump(preg_replace("/(\\[jkj|холо)/i", "<b>$0</b>", $contt)));

Then everything works fine, although the pattern is the same, just in the first case it is in the form of a variable ...
Tell me how to solve this problem?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Melkij, 2016-03-08
@up_sweep

data from the user process preg_quote

A
Alexey S., 2016-03-08
@Winsik

Your code:

$query = "/(\\[jkj|холо)/i";
<?=var_dump(preg_replace("/".$query."/i", "<b>$0</b>", $contt)));

Substitute the first line into the second:
Do you notice anything?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question