Page 1 of 1
How to write a expression t.o...
Posted: Sat Oct 09, 2010 12:39 am
by andre3
Hi, is it possible to write a expression to work with preg match all/ preg match to return true if it finds a line in a file thats only a href tag, example:
It will return true for this;
A: <a href="link">link text</a>
and false if the line of code as anything other than A, even if its just a simple text. example:
B: <a href="link">link text</a><img src="img link" alt="title"/>
Re: How to write a expression t.o...
Posted: Sat Oct 09, 2010 5:09 pm
by ridgerunner
Try this:
Code: Select all
if (preg_match('%^<a href[^>]+>[^<>\n]+</a>$%im', $contents)) {
# Successful match (simple <a>...</a> link alone on a line)
} else {
# Match attempt failed
}
The ^ at the beginning forces the regex to only match at the beginning of a line while the $ at the end forces the regex to only match at the end of a line. Also the 'm' modifier makes both of these "anchors" work at line ends, in addition to matching the ends of the string as a whole.
Re: How to write a expression t.o...
Posted: Sun Oct 10, 2010 10:44 am
by andre3
ridgerunner wrote:Try this:
Code: Select all
if (preg_match('%^<a href[^>]+>[^<>\n]+</a>$%im', $contents)) {
# Successful match (simple <a>...</a> link alone on a line)
} else {
# Match attempt failed
}
The ^ at the beginning forces the regex to only match at the beginning of a line while the $ at the end forces the regex to only match at the end of a line. Also the 'm' modifier makes both of these "anchors" work at line ends, in addition to matching the ends of the string as a whole.
Well done, one more piece of magic I would like you to add to this for me. is it possible to write it where I can extract the link from the tag ? an the title of the link an store them in variables ?
Thanks for your help
Re: How to write a expression t.o...
Posted: Sun Oct 10, 2010 11:36 am
by andre3
I think I figured it out, thanks for your help
