Page 1 of 1

preg_match_all usage problem

Posted: Sun Jan 21, 2007 1:48 pm
by Swede78
I've been going through regex tutorials and just can't get this to work. From what I read, this should work. But, it doesn't. Any help is appreciated.

I'm trying to extract the text between class="green"> and </a>, and put any matches in an array. Later, I will extract just the text inbetween, as that's no problem. Here's what I have, which isn't working:

Code: Select all

$String = '<a href="blablabla" class="green">Text that I want to extract</a>';

$SearchPattern = "/class=\"green2\">.+</";

preg_match_all ( $SearchPattern, $String, $Results );

print_r($Results );

// results in Array ( [0] => Array ( ) )
Thanks for reading.

Posted: Sun Jan 21, 2007 2:33 pm
by feyd
class="green" is not class="green2"

;)

Posted: Sun Jan 21, 2007 8:31 pm
by Swede78
Ooops... But, that was just a typo here in my sample. My code should be...

Code: Select all

$String = '<a href="blablabla" class="green2">Text that I want to extract</a>'; 

$SearchPattern = "/class=\"green2\">.+</"; 

preg_match_all ( $SearchPattern, $String, $Results ); 

print_r($Results ); 

// results in Array ( [0] => Array ( ) )
And I'm still doing something wrong with the regex. I don't know why it doesn't work. I've tried many variations with no success.

$SearchPattern = '/class="green2">.+</';
$SearchPattern = "/class=\"green2\">(.)+</";
$SearchPattern = "/class=\"green2\">[.]+</";

... and many combinations of those differences.

Posted: Sun Jan 21, 2007 9:09 pm
by Ollie Saunders
You want: (.+)
The brackets denote what to capture.

Posted: Mon Jan 22, 2007 9:21 am
by Swede78
Yes, thank you... that did make a difference. However, it still didn't work until I remembered to strip the slashes of the string I was searching. Sorry to waste people's time. When working with something new, I always assume my problem is with the new function I'm working with, and not something simple like that.