0

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.

j08691
  • 204,283
  • 31
  • 260
  • 272
TJR
  • 6,307
  • 10
  • 38
  • 64

2 Answers2

1
// 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);
Ωmega
  • 42,614
  • 34
  • 134
  • 203
  • This solved the problem and it works fine! Thanks for your answer! I never heard about this function before - but now its saved in my head. – TJR Aug 21 '12 at 17:05
0

If I understand your question correctly, you want to replace text in a string - but the replacement is based purely off of the first character found in the match?

If this is right, you can use PHP's preg_replace_callback(). Something similar to the following should work:

function replace_callback($matches) {
    switch ($matches[0]) {
        case 'a': return 'whatever';
    }
}

$str = preg_replace_callback('/<([a-z]):([a-z]):([a-z])>/ig', "replace_callback", $str);
newfurniturey
  • 37,556
  • 9
  • 94
  • 102