Trouble with regex and preg_match() - can't get results to save

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!

Answers


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.


Need Your Help

RichTextBox removing unknown tags

wpf .net-3.5 richtextbox rtf

I'm using richtextbox to show rtf documents created with MS Word

How to store only zip files downloaded from other website

php html codeigniter

I am building a application based in codeigniter. Here I need to download only files that have .zip extension and upload in my local drive. But to do it I had been given a function named get_zip

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.