-6

I have a string like:

www.mydomain.com/product/$ID_PRODUCT$/ID_$ID_PRODUCT$

what I need is replace strings contained between '$' and '$', also deleting the strings delimiters ( which is '$' ) obtaining something like:

www.mydomain.com/product/1234/ID_1234

Thanks,

EDIT: Trying

$new_string = preg_replace('/(\$)(.*)(\$)/s', product->id, $string);

But it does not handle the second expression...

The demo of @stribizhev , given in comments below, worked for me!

Daniel Garcia Sanchez
  • 2,306
  • 5
  • 21
  • 35
  • 1
    It might turn out a rather basic task, did you try anything? If you just need to replace `$`+`not $ (1 or more)`+`$` with one value, it is really simple. – Wiktor Stribiżew Oct 30 '15 at 09:20
  • yes, I tried this: http://stackoverflow.com/questions/6875913/simple-how-to-replace-all-between-with-php ok, help me mate – Daniel Garcia Sanchez Oct 30 '15 at 09:22
  • 1
    The accepted answer there features a "wrong" regex. But you need a negated character class, true. – Wiktor Stribiżew Oct 30 '15 at 09:22
  • 1
    Have a look [here](http://stackoverflow.com/questions/25977999/delete-a-specific-lines-between-two-symbols-in-txt-file-php). And use a negated character class `[^$]+` instead of `.*`. Post the attempt if you fail to obtain expected result. – Wiktor Stribiżew Oct 30 '15 at 09:25
  • You can do this simply with str_replace – danjam Oct 30 '15 at 09:29
  • 2
    Have a look at [the demo](http://ideone.com/Ff6ka4). – Wiktor Stribiżew Oct 30 '15 at 09:34
  • Check [`\$[^$]+\$`](https://regex101.com/r/wH3zI3/1) – Tushar Oct 30 '15 at 09:34
  • 1
    @stribizhev demo ( http://ideone.com/Ff6ka4 ) worked for me! Thanks mate. – Daniel Garcia Sanchez Oct 30 '15 at 09:41
  • If the template string contains a single placeholder (`$PRODUCT_ID$`, f.e.) then you don't need `regexp`. Just use [`str_replace()`](http://php.net/manual/en/function.str-replace.php). If there are many possible placeholders then you need a way to identify what placeholder was found in order to know what replacement to use. [`preg_replace()`](http://php.net/manual/en/function.preg-replace.php) doesn't help in this case. You can use [`preg_replace_callback()`](http://php.net/manual/en/function.preg-replace-callback.php) but, again, `str_replace()` is enough, easier to use and more readable. – axiac Oct 30 '15 at 10:26

1 Answers1

1

This seem to work:

<?php
$a = 'www.mydomain.com/product/$ID_PRODUCT$/ID_$ID_PRODUCT$';
echo preg_replace('/[$][a-zA-Z_]+[$]/',"1234",$a);

Demo

Thamilhan
  • 13,040
  • 5
  • 37
  • 59