bob_the_coder Posted January 26, 2014 Share Posted January 26, 2014 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 Quote Link to comment Share on other sites More sharing options...
kicken Posted January 26, 2014 Share Posted January 26, 2014 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. Quote Link to comment Share on other sites More sharing options...
bob_the_coder Posted January 26, 2014 Author Share Posted January 26, 2014 hmm, I have no idea how that's supposed to work. I just tried it and it's not working. Regex is not my strong suit. Quote Link to comment Share on other sites More sharing options...
.josh Posted January 26, 2014 Share Posted January 26, 2014 @kicken that first word boundary won't work, because " /issue.." has 2 non-word chars in a row (the space and then forward slash). IOW it has to be [non-word char]\b[word char] Quote Link to comment Share on other sites More sharing options...
Solution .josh Posted January 26, 2014 Solution Share Posted January 26, 2014 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 Quote Link to comment Share on other sites More sharing options...
bob_the_coder Posted January 26, 2014 Author Share Posted January 26, 2014 Thanks Josh, the first suggestion worked perfectly. Thank you both for your help. I really appreciate it. -Bob Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.