Hints and tips on regex

These are some helpful hints on various topics.

 

Dash in regular explession

There is something you should know if you want to use a dash in ereg() matching. For example if you want to check if a string contains only letters, digits, dots and dashes, you should put the dash at the end of the list. Also unlike the dot don't put a backslash before it:
ereg('^[a-zA-Z0-9\.-]+$', $string)

Regex for getting the content of given span by id or class

Here's a regex that extracts content of span with given id or class from an HTML text contained in $data variable:

$regex = '/\<span\s*class=[\'"]?classname[\'"]?\s*>([^\<]+)\<\/span\>/imu';
preg_match_all($regex, $data, $matches, PREG_PATTERN_ORDER);
print_r($matches[1]);

$regex = '/\<span\s*id=[\'"]?spanid[\'"]?\s*>([^\<]+)\<\/span\>/imu';
preg_match_all($regex, $data, $matches, PREG_PATTERN_ORDER);
print_r($matches[1]);