0

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?

4
  • 2
    $lineOfValue = preg_replace("/.*$text[\"', ]*/", "", $line); Where is the problem?! Commented Feb 23, 2015 at 8:14
  • Getting this error when adding like your reply : Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in D:\xampp\htdocs\wordpresstest\write.php on line 12 Commented Feb 23, 2015 at 8:19
  • Then just concatenate it: $lineOfValue = preg_replace("/.*" . $text . "[\"', ]*/", "", $line); ?! Commented Feb 23, 2015 at 8:23
  • If the contents of $text is guaranteed to be safe for use in the expression you can use "/.*{$text}[\"', ]*/" as well, wrapping the variable references in curly braces. Commented Feb 23, 2015 at 8:44

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

The expression delimiter should also be escaped.
Good call - I've edited the example to show the use of preg_quote()'s optional second parameter

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.