I want to add a variable in preg_replace.
for Ex :-
In this blelow line of code, I want to add $text instead of "sometext"
$text = "sometext";
$lineOfValue = preg_replace("/.*sometext[\"', ]*/", "", $line);
Can any one help me?
In a regular expression the $ symbol signifies the end of the string being processed, therefore including a variable within a regular expression as suggested by @Rizier123 won't work.
Instead the variable should be concatenated into the regular expression as follows to avoid the $ being misinterpreted:
$text = 'sometext';
$lineOfValue = preg_replace("/.*" . $text . "[\"', ]*/", "", $line);
Also - if your $text variable may contain any character, you should consider using preg_quote() to make the string safe for use within a regular expression:
$text = 'sometext';
$lineOfValue = preg_replace("/.*" . preg_quote($text, '/') . "[\"', ]*/", "", $line);
$lineOfValue = preg_replace("/.*$text[\"', ]*/", "", $line);Where is the problem?!$lineOfValue = preg_replace("/.*" . $text . "[\"', ]*/", "", $line);?!$textis guaranteed to be safe for use in the expression you can use"/.*{$text}[\"', ]*/"as well, wrapping the variable references in curly braces.