0

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!

1
  • 1
    kingkero has the answer. As an aside comment, I suggest you to replace .* by something else more explicit, this will reduce the regex engine work and avoid possible errors. Commented Mar 5, 2014 at 22:33

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

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.