Search code examples
phpregexpreg-replacepreg-split

Search for matches and save and maybe replace it


i'll try to explain my question in the best way i can ... okay.

i have a multi line string like this:

Hello World
And again Hello <a:b:c>
And again ...

Now i want to replace but it depents on what is the first letter, the second and so on. I have a regex snippet to get an array with the 3 arguments.

arr = ('a', 'b', 'c')

now i have a switch to analyse the first argument.

switch (arr[0]) {
         case 'a':
              // do this
         [...]
}

if the first argument is a i want to replace <a:b:c> with something.

The question is now: To get the arguments i use preg_split. How its now possible to replace the right part of the string ? I can get the position with PREG_SPLIT_OFFSET_CAPTURE but its a multi line string, and (!) when i replace with something the position of the other matches (there are n-matches possible) must be change too, right ?

Maybe you have a solution to solve this ?

I thought preg_replace could be work, but i think this is the wrong function to solve this, because an letter (for example the second, b) can be a parameter that is dynamic. Maybe i understood the function preg_replace in the wrong way ... but ... i really dont know how to solve this. Maybe you have a documentation where i can read something to solve this problem (please dont link me to php.net - i already read it) or you have a an idea.


Solution

  • // This function will replace specific matches into a new form
    function RewriteText($Match)
    {
      $EntireSection = $Match[0];
      $GroupOne = $Match[1];
      // ...
      return $Value;
    }
    
    $NewText = preg_replace_callback('/Hello\s+(\S+)/i', "RewriteText", $Text);