Jump to content

[SOLVED] Preg_match difficulties.


Joesavage

Recommended Posts

To start: im not good with regex.

All i want to do is capture all of the information inbetween <!-- Begin Description --> and <!-- End Description -->. In the example i have below i only have 'k' and i cant even get that to work. In real life i want to be able to capture text with new lines and white text and other weird characters.

 

$data = "<!-- Begin Description -->k<!-- End Description -->";
$regex = '/"<!-- Begin Description -->(.+?)<!-- End Description -->/';
preg_match_all($regex,$data,$description,PREG_SET_ORDER);
print_r ($description);

 

The description array gets printed out empty. Any ideas why? I have tried using (.+?), (.*), and (.*?). These are all snippets that i have seen used other places.

Link to comment
https://forums.phpfreaks.com/topic/123994-solved-preg_match-difficulties/
Share on other sites

Code:

<?php
$data = "<!-- Begin Description -->k<!-- End Description -->";
$regex = '/\Q<!-- Begin Description -->\E(.+?)\Q<!-- End Description -->\E/s';
preg_match_all($regex,$data,$description);
print_r ($description);

 

Output:

Array
(
   [0] => Array
       (
           [0] => <!-- Begin Description -->k<!-- End Description -->
       )

   [1] => Array
       (
           [0] => k
       )

)

 

$description[1] will be a multi-dim array of the matches in between the tags.

 

EDIT:  I don't know why I just used \Q...\E, but whatever.  Doesn't matter.  Makes it easier to change it in the future maybe? *shifty eyes*

EDIT:  I don't know why I just used \Q...\E, but whatever.  Doesn't matter.  Makes it easier to change it in the future maybe? *shifty eyes*

 

It does matter. If it's not required, don't do it. Otherwise, you'll have the next coder wondering what the intention was.

damn... /s makes it work perfectly. Thank you very much.

 

Actually, the real reason it was failing was because of the " in front of the expression.  The s modifier is to make . match \n as well as every character.

 

@effigy: That's what comments are for. ;)  That's beside the point.  I didn't feel like going and taking it out, so I just added that comment at the bottom.  =P

@effigy: That's what comments are for. ;)  That's beside the point.  I didn't feel like going and taking it out, so I just added that comment at the bottom.  =P

 

No. Comments are not for worthless code additions, but for seemingly confusing and/or complex ones. You decided to add 140 characters to your post rather than remove 8? Interesting.

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.