0

I have a string like this:

$str = "This product price is 23,39 and sale end after 29th June";

I need to replace two characters after "," with ".-", so the output like:

This product price is 23.- and sale end after 29th June

I tried with but it remove last 3 characters:

 echo substr($string, 0, strlen($string) - 3);

Please help me to solve this issue.

3
  • 1
    A regex would be easier than substr. With substr you'll need to find the first occurance and use that in place of the 0. e.g. strpos. Commented May 31, 2018 at 18:00
  • 1
    $string is not $str Commented May 31, 2018 at 18:02
  • It is not clear what you are doing in the code. The second line of code addresses a different string variable than the first. Also, you don't seem to search for ,. Commented May 31, 2018 at 18:02

1 Answer 1

2

First I will try to select the string that needs to be replaced:

substr($str, strpos($str, ","), 3);
// Gives me ,39 - 3 characters from the ,.

And now I'll replace it with the .--

<?php
  $str = "This product price is 23,39 and sale end after 29th June";
  echo str_replace(substr($str, strpos($str, ","), 3), ".--", $str);
?>

This gives me an output:

This product price is 23.-- and sale end after 29th June

Is this what you need? This is simple and doesn't need a RegEx. Not sure if RegEx will be more efficient in this case. I would go about doing this way.

Sign up to request clarification or add additional context in comments.

2 Comments

@user3783243 Ha ha ha... True that. I just added the more info.
@user3783243 Yay!

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.