1
$subject = "'foo' = 'bar'";
$pattern = "/('foo' = ').*(')/";
$var = "123baz";
$replacement = "$1$var$2";
print_r(preg_replace($pattern, $replacement, $subject));

Result is 23baz' instead of 'foo' = '123baz'. Why and how can I fix this?

Rizier123
  • 58,877
  • 16
  • 101
  • 156
a1277399
  • 27
  • 7

1 Answers1

2

Think you're looking for something like this:

$subject = "'foo' = 'bar'";
$pattern = "/(= ').*(')/";
$var = "123baz";
$replacement = "= '$var'";
print_r(preg_replace($pattern, $replacement, $subject));

Output:

'foo' = '123baz'
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Rizier123
  • 58,877
  • 16
  • 101
  • 156
  • @a1277399 You're using a wrong pattern and so your replacement is wrong! your searching for: `'foo' = '*'`So you replace everything which matches this pattern with the replacement – Rizier123 Dec 11 '14 at 20:55
  • @a1277399 yeah you could use it, but `$1` means the first `()` group get's replaced there, but since the variable at the start have a number it tries to replace it whith the `()` 1123 group which doesn't exists – Rizier123 Dec 11 '14 at 21:04
  • That is, what I was assuming. How can I avoid this? – a1277399 Dec 11 '14 at 21:16
  • @a1277399 Out of my head i don't think that's possible, so for now my answer should work. – Rizier123 Dec 11 '14 at 21:17
  • @a1277399 Your welcome! Have a nice day :D (I'll take a look if i find something, because it's very interesting!) – Rizier123 Dec 11 '14 at 21:19
  • Thank you! Have a nice day, too! ;-) (That would be great! Actually a solution for that is exactly what I'm looking for.) – a1277399 Dec 11 '14 at 21:22
  • @a1277399 Since it's very iteresting you could make a new question if you want and describe your problem well and show the people where you stuck, what the problem is! I think with this way you get more people to look at and you get your answer faster! (Also make sure you tag it with `regex`) – Rizier123 Dec 11 '14 at 21:24
  • Well, I don't really know how to better describe the problem. :-/ – a1277399 Dec 11 '14 at 21:29
  • @a1277399 Have to solution! (It's every time the simplest Xd) just use `$replacement = '${1}' . $var . '${2}';` (With `{}` your like exactly say which number it is) – Rizier123 Dec 11 '14 at 21:33
  • Does this work with PHP 5.2.17? Because with `$replacement = "${1}" . $var . "${2}";` I get `baz`. – a1277399 Dec 11 '14 at 21:54
  • Ups. You actually have to use single quotes. Do you know why? Thank you very much for your kind help. :) – a1277399 Dec 11 '14 at 21:56
  • @a1277399 Yes because there is a difference between single and double quotes!(http://stackoverflow.com/q/3446216/3933332) If you put it in double quotes first the $ get's 'calculated' and php thinks it's a variable not a regex expression, so if you put it in single quotes that doesn't happen – Rizier123 Dec 11 '14 at 21:58
  • 1
    I was aware of the difference, but not in that context. Thank you! – a1277399 Dec 11 '14 at 22:01