0

I am working with php. I have some dynamic string. Now I want to add some number after some string. Like, I have a string this is me (1). Now I want to add -7 after 1. So that string should be print like this this is me (1-7). I have done this properly by using substr_replace. like this

substr_replace('this is me (1)','-59',-1,-1)

Now if there is more than one number like this this is me(2,3,1). I want to add -7 after each number. like this one this is me(2-7,3-7,1-7).

Please help. TIA

1
  • 2
    You might want to take a look at preg_replace() Commented Jul 16, 2018 at 12:27

1 Answer 1

2

I dont know if there is a good way to do this in one or two lines, but the solution I came up with looks something like this:

$subject = "this is me (2,3,1)";

if (preg_match('[(?<text>.*)\((?<numbers>[0-9,]+)\)]', $subject, $matches)) {
  $numbers = explode(",", $matches['numbers']);
  $numbers = array_map(function($item) {
      return $item.'-7';
  }, $numbers);

  echo $matches['text'].'('.implode(",", $numbers).')';
}

What happens here is the following:

  1. preg_match checks whether the text is in our desired format
  2. We generate an array from our captured named group numbers with explode
  3. We add our "Magic Value" (-7) to every array element
  4. We're joining the text back together
Sign up to request clarification or add additional context in comments.

1 Comment

Wow. great. You solved my problem . Thank you so much .

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.