简体   繁体   中英

How to add string after specific character in PHP

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM