Tommy B.
Tommy B.

Reputation: 3679

Using a replace pattern in preg_replace replacement parameter

I'm trying to use PHP's preg_replace to replace every #CODE-123 kind of token to /CODE-123.

It works pretty well except for one last detail, I'd need to remove the # from the string the second time I use it but I cannot figure out how.

Here's what I have so far:

echo preg_replace('/#.*-[0-9]*/i', '[${0}](/${0})', $this->description);

It works and replaces #CODE-123 to [#CODE-123](/#CODE-123) but I'd need it to be [#CODE-123](CODE-123) instead.

Any idea? Thanks!

Upvotes: 0

Views: 55

Answers (1)

kero
kero

Reputation: 10658

If you group it (with brackets (..)), you can address each of the found independently

echo preg_replace('/#(.*-[0-9]*)/i', '[${0}](${1})', $this->description);

The whole pattern will always be recognized by 0 (what you already use), and the first group by 1, etc. You might want to add ? to make the pattern not greedy.

Currently it works like this:

$text = "hello world #ACODE-123 blabla #BCODE-233";
echo preg_replace('/#(.*-[0-9]*)/i', '[${0}](${1})', $text);
//hello world [#ACODE-123 blabla #BCODE-233](ACODE-123 blabla #BCODE-233)

Which is most likely not the wanted result (but valid!).

$text = "hello world #ACODE-123 blabla #BCODE-233";
echo preg_replace('/#(.*?-[0-9]*)/i', '[${0}](${1})', $text);
                 //     ^-- this is new
//hello world [#ACODE-123](ACODE-123) blabla [#BCODE-233](BCODE-233)

Upvotes: 2

Related Questions