本文介绍了如何在PHP中的锚标记之间提取文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在名为$message的变量中有一个字符串,如下所示:

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>';

在这种情况下,我只想在锚标记中获取文本,即 TEST PRA .

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?

谢谢.

推荐答案

使用preg_match_all函数进行全局匹配.

Use preg_match_all function inorder to do a global match.

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

在这里preg_match就足够了. \K会丢弃最终匹配的先前字符,直到最终打印为止,因此它将不考虑先前匹配的>字符.您也可以使用正向后视代替\K,例如(?<=>). [^<>]*否定的字符类,它与零个或多个字符匹配但不匹配<>的任何字符. (?=<),积极的超前断言,断言匹配必须后跟<字符.

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.

演示

$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]);

输出:

TEST PRA

这篇关于如何在PHP中的锚标记之间提取文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 13:12