ajsie
ajsie

Reputation: 79756

Get visible text from HTML hyperlink

How can I match the text "Cats" within the link element?

<A HREF="http://www.catingale2?subject=10023">Cats</A> forum

Upvotes: -1

Views: 106

Answers (4)

codaddict
codaddict

Reputation: 455192

$input = '<A HREF="http://www.catingale2?subject=10023">Cats</A> forum';
if(preg_match('{<a.*?>(.*?)</a>}i',$input,$matches)) {
    $hyperlinked = $matches[1];
}
echo $hyperlinked; // print Cats

The regex used is: <a.*?>(.*?)</a>

Explanation:

<a.*?> - an opening anchor tag with any attribute.
(.*?)  - match and remember between opening anchor tag and closing anchor tag.
</a>   - closing anchor tag.
i      - to make the entire matching case insensitive

Upvotes: 1

Tomislav Nakic-Alfirevic
Tomislav Nakic-Alfirevic

Reputation: 10173

<a[^>]*>([^<]*)<\/a>

That's it. You could probably get away with:

<a[^>]*>(.*)<\/a>

or

<a[^>]*>([^<]*)

Upvotes: 2

ghostdog74
ghostdog74

Reputation: 342591

no need regex

$str=<<<EOF
<A HREF="http://www.catingale2?subject=10023">Cats</A> forum
<A HREF="http://www.catingale2?subject=10024">
 Dogs</A>
forum
EOF;
$s = explode("</A>",$str);
foreach($s as $v){
    if (strpos($v,"<A HREF")!==FALSE){
       $t=explode(">",$v);
       print end($t)."\n";
    }
}

output

# php test.php
Cats

 Dogs

Upvotes: 2

Pascal MARTIN
Pascal MARTIN

Reputation: 401062

What about something like this :

$str = '<A HREF="http://www.catingale2?subject=10023">Cats</A> forum';
$matches = array();
if (preg_match('#<a[^>]*>(.*?)</a>#i', $str, $matches)) {
    var_dump($matches[1]);
}

Which gives :

string(4) "Cats" 


And, as a sidenote : generally speaking, using regex to "parse" HTML is not quite a good idea !

Upvotes: 3

Related Questions