How to write a expression t.o...

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

Moderator: General Moderators

Post Reply
andre3
Forum Newbie
Posts: 5
Joined: Sat Oct 09, 2010 12:20 am

How to write a expression t.o...

Post 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"/>
User avatar
ridgerunner
Forum Contributor
Posts: 214
Joined: Sun Jul 05, 2009 10:39 pm
Location: SLC, UT

Re: How to write a expression t.o...

Post 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.
andre3
Forum Newbie
Posts: 5
Joined: Sat Oct 09, 2010 12:20 am

Re: How to write a expression t.o...

Post 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
andre3
Forum Newbie
Posts: 5
Joined: Sat Oct 09, 2010 12:20 am

Re: How to write a expression t.o...

Post by andre3 »

I think I figured it out, thanks for your help :) :drunk:
Post Reply