Jump to content

Creating 'slash' links


bob_the_coder

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
https://forums.phpfreaks.com/topic/285680-creating-slash-links/
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.

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.