1

The code below is not a functioning method it's just written to help you understand what I'm trying to do.


// $i = occurrence to replace
// $r = content to replace

private function inject($i, $r) {
      // regex matches anything in the format {value|:value}
      $output = preg_replace('/\{(.*?)\|\:(.*?)\}/', '$r', $this->source);
      $output[$i]
}

How do I find the $i occurrence in $output; and replace it with $r;?

Note: All I want to do is use $i (which is a number) to find the occurrence of that nmber in a preg_replace; For exmaple: I might want to replace the second occurrence of the preg_replace pattern with the variable $r

4
  • Does $i contain a regex or a string you want to find? Commented Apr 1, 2011 at 21:58
  • what's in $i? the whole pattern? Needs some more details. Commented Apr 1, 2011 at 21:59
  • The occurrence number of the matched item. $i for example could be 1 then, regex needs to find the 1 occurence and replace it with $r; Commented Apr 1, 2011 at 22:00
  • @willm1 the number of the string occurrence. Commented Apr 1, 2011 at 22:08

1 Answer 1

1

I think you can only accomplish such an occurence counting with a callback:

private function inject($i, $r) {
      $this->i = $i;
      $this->r = $r;

      // regex matches anything in the format {value|:value}
      $output = preg_replace_callback('/\{(.*?)\|\:(.*?)\}/',
                array($this, "inject_cb"), $this->source);
}

function inject_cb($match) {
    if ($this->i --) {
        return $match[0];
    }
    else {
        return $this->r;
    }
}

It leaves the first $i matches as is, and uses the tempoary $this->r once when the countdown is matched. Could be done with a closure to avoid ->$i and ->$r however.

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

3 Comments

Can't seem to get this working? I'm sure it is probably an error on my part.
It needs to do something with $output still. An alternative option for this task would be preg_split with PREG_SPLIT_DELIM_CAPTURE maybe (but more fiddly).
I think these two functions need to be wrapped inside a class (as methods) for this to work.

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.