1

I'm building a dynamic linking system for one of the websites that I'm working on, so that you can just put something like {_LINK_20_} and it will dynamically input either the onclick event or href attribute depending on if the user has javascript enabled or disabled.

The only problem is that I was using a loop to go through the document originally, but I realized that a regular expression would work much better so that I can have link ID's that are non-consecutive and it will still detect them.

I'm just testing this in a sample page before I try to impliment it into my OOP backend, so here is the sample code:

$results = array();
$string = 'asdfasdf {_LINK_2_} asdf {_LINK_1_}{_LINK_3_} asdf{_LINK_8_}';
$exp = '/{_LINK_<0-9>+_}/';
$find = preg_match($exp, $string, $results);

However, the array $results has no results when I output it with print_r(). I'm pretty much a complete novice at regex syntax, so please go easy on me. :)

What I'm really trying to do is only save the number from the matched text so that I can just loop through the regex results and replace each link as needed without having to call preg_replace() or str_replace().

I've also tried the preg_match_all() function but it didn't work either. Thanks in advance, sorry I'm so bad at regular expressions!

SISYN
  • 2,209
  • 5
  • 24
  • 45

1 Answers1

2

Try this regular expression:

$exp = '/{_LINK_[0-9]+_}/'

And use preg_match_all.

Character classes are implemented with square brackets ('[]'), instead of angle brackets ('<>'). Simply using the correct brackets will make your regular expression work.

If you really want to save just the number, you can use this regex:

$exp = '/(?<={_LINK_)[0-9]+(?=_})/'

Click here to see it in RegExr. It works by using a lookbehind and a lookahead, which are zero width assertions (meaning they match between characters, instead of matching the characters themselves) about what is behind or ahead of your other Regular Expressions.

See it here on ideone.com.

FrankieTheKneeMan
  • 6,645
  • 2
  • 26
  • 37
  • 1
    Thanks, that was very helpful I got it working now! +1 on the answer and accepted it. – SISYN Jan 23 '13 at 23:25
  • Actually, `{` and `}` are only treated as special characters in the following situations: `{5}` (exact number of times), `{5,}` (minimum number of times up to infinity) , `{5,42}` (range of times). In the provided regex they would have matched themselves. They are the only metacharacters that behave this way. However, it is good practice to escape them anyway. – CJ Dennis Nov 28 '13 at 06:39
  • @CJDennis [it seems you're right](http://ideone.com/vb5kt5), in PHP anyway. Though, I disagree that it's "good practice" to escape them anyway. You should escape only what needs escaping, and nothing else. It helps enforce your own understanding of what the string contains, and what the the regex parser is seeing/expecting. I'll edit my response to reflex this. – FrankieTheKneeMan Dec 02 '13 at 16:07