[SOLVED] Regular expression throwing error

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

Moderator: General Moderators

Post Reply
chocolatetoothpaste
Forum Newbie
Posts: 10
Joined: Wed Sep 06, 2006 10:48 am

[SOLVED] Regular expression throwing error

Post by chocolatetoothpaste »

Hey all,
I am using a regular expression to break down links in the <a href> tag. I am using the regular expression below:

Code: Select all

preg_match_all("<a[\s]+[^>]*?href[\s]?=[\s\"\']*(.*?)[\"\']*.*?>([^<]+|.*?)?<\/a>",$data,$title_matches);
but it causes this error:

Code: Select all

Warning: preg_match_all(): Unknown modifier ']' in /home/content/k/o/s/koskan/html/realtor_contact.php on line 11
Can anyone see anything wrong with my regex?
Last edited by chocolatetoothpaste on Wed Sep 20, 2006 9:34 am, edited 1 time in total.
User avatar
n00b Saibot
DevNet Resident
Posts: 1452
Joined: Fri Dec 24, 2004 2:59 am
Location: Lucknow, UP, India
Contact:

Post by n00b Saibot »

if you would have studied the regex guide carefully, you would have known that the first character in the regex pattern is used as delimiter for the pattern i.e. it serves as boundary for your regex string.

look at your regex... the first character is '<'. so it is being used a delimiter for thr regex string.. and now when the regex engine finds the second occurence of the same string (delimiter) it saves the string upto that point as regex and characters next to delimiters are parsed as modifiers for the regex string... in this case a ']' is not a valid modifier.. hence the pretty error message...

changing the regex to following will do away with the error:

Code: Select all

preg_match_all("#<a[\s]+[^>]*?href[\s]?=[\s\"\']*(.*?)[\"\']*.*?>([^<]+|.*?)?<\/a>#",$data,$title_matches);
look how in this case I have defined # as my regex delimiter and it works normally...

in your leisure time be sure to read the regex syntax on php site.
Last edited by n00b Saibot on Wed Sep 20, 2006 9:35 am, edited 2 times in total.
chocolatetoothpaste
Forum Newbie
Posts: 10
Joined: Wed Sep 06, 2006 10:48 am

Post by chocolatetoothpaste »

Wow! That worked. I didn't know the delimiters worked that way. I certainly will read up on regexes, but I have an immediate issue. Now I find out that my regex isn't working properly! :cry: Thanks for the help.
User avatar
n00b Saibot
DevNet Resident
Posts: 1452
Joined: Fri Dec 24, 2004 2:59 am
Location: Lucknow, UP, India
Contact:

Post by n00b Saibot »

this will match all the attributes of the anchor tag and you may then use the ones you like...

Code: Select all

preg_match("#<a([^>]+)>(.*?)</a>#is", $data, $matches)
then you will have list of attributes in $matches[1] array which you can explode() and use any of them at your will. no funky regex required... :)
Post Reply