Actually such an expression:

preg_match("/$a(.*?)/i",$text,$matches); 

I cannot put text into single quotes, since the $a variable will not be processed, and it produces an error with double quotes. How to use the variable in the source text of the regular?

3 answers 3

Write the $ a variable in the parentheses of the preg_quote () function, and the preg_quote () function in the template inside your template using concatenation:

 preg_match('~'. preg_quote($a, '~') .'(.*?)~i', $text, $matches); 

    It is possible so:

     preg_match("/\\Q$a\\E(.*?)/i", $text, $matches); 

    You can read more about \ Q \ E here: PCRE: Escape sequences

    • This option is preferable, as it is faster than using the preg_quote() function. - Visman
    • I tested \Q and \E , for some reason they don’t cope with the symbol denoting the regular border :( In this case, if the symbol / found in $a , preg_match() returns false . - Visman

    As a variant preg_match(sprintf("/%s(.*?)/i", $a),$text,$matches);