Jump to content

Archived

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

heavyEddie

preg_match_all and the array

Recommended Posts


I'm trying to find all the filenames in some large text articles.  They are flagged nicely like so... [b]{FILE:test.html}[/b].  I would then like all the text files dropped into an array to work with.  My code looks like this.
[code]preg_match_all("/\{FILE:(.*)\}/s", $article, $matches);[/code]

If using preg_match, it will output to $matches[1] with the name of the file perfectly.  However, with preg_match_all it all goes to heck.  So,  I guess the questions are...
[list]
[*]Is the regex correct?
[*]How do I use the $matches array to get my list of filenames?
[/list]

I'm VERY new to regex, so any help would be greatly appreciated.  Didn't find much with a search.  Almost all array reference just say to use $match[1] with a regular preg_match.

Share this post


Link to post
Share on other sites
you're well on your way. with preg_match_all, you've got to allow for another dimension in your array. there are also flags you can set to help you get what you need in an easily managed order. try this and see if it helps:
[code]
<?php
preg_match_all("/\{FILE:(.*)\}/s", $article, $matches, PREG_PATTERN_ORDER);
foreach ($matches[1] as $file) {
  echo "$file<br />\n";
}
?>
[/code]

if all goes well, your filenames should be in the $matches[1] array.

hope this helps!

Share this post


Link to post
Share on other sites
I tried something very similar... thanks for the reply!  However, I think my regex may be screwing because your code produces the following.
[code]test1.html}
{FILE:test2.html[/code]

Share this post


Link to post
Share on other sites
[quote author=heavyEddie link=topic=112345.msg456090#msg456090 date=1161568102]
I tried something very similar... thanks for the reply!  However, I think my regex may be screwing because your code produces the following.
[code]test1.html}
{FILE:test2.html[/code]
[/quote]

it may be because you had .* as you match for your filename, and the star is greedy. try this instead:
[code]
<?php
preg_match_all("/\{FILE:(.*?)\}/s", $article, $matches, PREG_PATTERN_ORDER);
foreach ($matches[1] as $file) {
  echo "$file<br />\n";
}
?>
[/code]

just tested it, and it works great for me.

Share this post


Link to post
Share on other sites

×

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.