Jump to content

preg_match_all and the array


heavyEddie

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.
Link to comment
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!
Link to comment
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.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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