Jump to content

Creating 'slash' links


bob_the_coder
Go to solution Solved by .josh,

Recommended Posts

Hey all, I'm not really sure what this is technically called, but I'm working on a small application and need to be able to "link" issue tickets to each other. What I have is a comment string, lets go with "this is very similar to /issue/14001, can probably be deleted" I'd like to replace "/issue/14001" with "<a href='viewissue.php?id=14001'>14001</a>".

 

I can do a str_replace to replace the /issue/ but I can't seem to figure out how to get the 14001 part of the string.... I'm guessing it's some kind of Regex, but I can not figure it out at all. I'm hoping someone here could give me a hand.

 

Thanks for any help that can be provided,

BTC

Link to comment
Share on other sites

If the /issue/ part is constant and only the number varies then you would use a regex like this:

$str = preg_replace('~\b/issue/(\d+)\b~', '<a href="/issue/$1">/issue/$1</a>', $str);
That will find any instance of /issue/ followed by a sequence of digits and replace it with the link. The $1 in the replacement string is a back-reference to the first parenthesized group which is the issue number.
Link to comment
Share on other sites

  • Solution

Basically you need to do this, which will match no matter what comes before it:

 

$str = preg_replace('~/issue/(\d+)\b~i', '<a href="/issue/$1">/issue/$1</a>', $str);
Or this, which uses a negative lookbehind as a workaround for what kicken posted. (it will only match if it's preceded by a non-word char):

 

$str = preg_replace('~(?<=\W)/issue/(\d+)\b~i', '<a href="/issue/$1">/issue/$1</a>', $str);
I also threw in a case-insensitive modifier so it will match if someone does /ISSUE/123
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.