preg_match_all usage problem

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
Swede78
Forum Contributor
Posts: 198
Joined: Wed Mar 12, 2003 12:52 pm
Location: IL

preg_match_all usage problem

Post 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.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

class="green" is not class="green2"

;)
Swede78
Forum Contributor
Posts: 198
Joined: Wed Mar 12, 2003 12:52 pm
Location: IL

Post 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.
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

You want: (.+)
The brackets denote what to capture.
Swede78
Forum Contributor
Posts: 198
Joined: Wed Mar 12, 2003 12:52 pm
Location: IL

Post 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.
Post Reply