Florian Müller
Florian Müller

Reputation: 7785

handle parts of string in preg_replace_callback differently

I got a string in which I replace all occurrences of [CODE]...[/CODE]. With preg_replace_callback can I call a function which handles the content of those tags. But how can I manipulate all string which are around those occurrences?

Example:

$str = "Hello, I am a string with [CODE]some code[/CODE] in it";

Now, with preg_replace_callback I manipulate the content of [CODE], in this case some code. But I'd like for all other text in this string, so Hello, I am a string with and in it to do something different. How could I do this the best way?

Thank you for you help!

Flo

Upvotes: 0

Views: 64

Answers (1)

menacingly
menacingly

Reputation: 738

It'd be simpler if I could see the regex, but the gist is that I think you want capture groups.

You should be able to access those regions separately by placing them into parenthesis-wrapped groups. Each section will be available to your callback. So (crudely) something like /(.*)(\[CODE\].*\[/CODE\])(.*)/ should pass an array of matches to your callback

Upvotes: 2

Related Questions