PHPLover
PHPLover

Reputation: 12957

How to extract the text between anchor tag in PHP?

I've one string in a variable titled $message as follows :

$message = 'posted an event in <a href="http://52.1.47.143/group/186/">TEST PRA</a>';

I only want to get the text within anchor tag i.e. TEST PRA in this case using PHP.

How should I do this in an efficient way? Can someone please help me in this regard?

Upvotes: 2

Views: 6705

Answers (2)

Tahi Reu
Tahi Reu

Reputation: 590

Regex may be slow sometimes. Also, regex approach is maybe not 100% reliable if some unexpected HTML is being passed to it.

So I would rather do it this way:

$temp = new DOMDocument;
$temp->loadHTML($message);
$anchors = $temp->getElementsByTagName('a');
foreach ( $anchors as $anchor ) {
    echo $anchor->textContent;
}

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174706

Use preg_match_all function inorder to do a global match.

preg_match_all('~>\K[^<>]*(?=<)~', $str, $match);

Here preg_match would be enough. \K discards the previously matched characters from printing at the final, so it won't consider the previouslly matched > character. You could use a positive lookbehind instead of \K also , like (?<=>). [^<>]* Negated character class, which matches any character but not of < or >, zero or more times. (?=<), Positive lookahead assertion which asserts that the match must be followed by < character.

DEMO

$str = 'posted an event in <a href="http://52.1.47.143/group/186/">TEST PRA</a>';
preg_match('~>\K[^<>]*(?=<)~', $str, $match);
print_r($match[0]);

Output:

TEST PRA

Upvotes: 7

Related Questions