MyBB Community Forums

Full Version: RegEx help :)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm having trouble getting my regex pattern to work. I've never been very good at it, and don't really know how it works in PHP.

From my understanding, I have to use preg_match_all to get all occurrences of a particular pattern correct?

This is what I want:

I have pages on my site like:
<a href="http://tomkent.me/user-12345.html">User1</a>

I want to get the User1 bit of the html, from a page containing about 50 of these URLs Smile

I tried:

preg_match_all('<a href="http://tomkent.me/user-(.*).html">(.*?)</a>',$html,$matches);

as well as (escaping some things):
preg_match_all('<a href\=\"http\:\/\/tomkent\.me\/user\-(.*)\.html\">(.*?)<\/a>',$html,$matches);

But neither work when I try to output:
print_r($matches);


Any help would be appreciated Toungue
Give this a try:
http://gskinner.com/RegExr/

Smile
Also this, I find it very useful at times when I need:

http://regexlib.com
ok, so I made a pattern that works, but PHP gets no output to the $matches array Sad


<a href="http://tomkent.me/user-(.*?).html">(.*?)</a>

Matches, both groups perfectly using that site, but PHP gets nothing Sad I checked that it is getting the HTML, which it is. Sad
Also check out http://codular.com/regex

EDIT: Could you perhaps post the whole code?
The whole code is pretty simple Toungue

$user = "http://tomkent.me/page-1.html";
$html = file_get_contents($user);

//debug: echo $html;

preg_match_all('<a href="http://tomkent.me/user-(.*?).html">(.*?)</a>',$html,$matches);

print_r($matches);

Note: The page I'm looking at is super secret, so I modified the link Toungue But, I can guarantee the HTML is loaded into $html Smile
Ok, here's my code:

<?php

$message = "Hello <a href=\"http://tomkent.me/user-3.html\">Euan</a>";

$pattern = "#\<a href\=\"http\://tomkent.me/user-(?:\d*).html\"\>(.*?)\</a\>#i";

preg_match_all($pattern, $message, $match);

echo "<pre>";
var_dump($match);
echo "</pre>";

And the output:

array(2) {
  [0]=>
  array(1) {
    [0]=>
    string(48) "Euan"
  }
  [1]=>
  array(1) {
    [0]=>
    string(4) "Euan"
  }
}

Smile Seems to work.
Thanks Smile That seems to work fine Toungue I have no idea why mine didn't :/ Other than escaping the pattern (possibly the problem?)