简体   繁体   English

如何在PHP中的定位标记之间提取文本?

[英]How to extract the text between anchor tag in PHP?

I've one string in a variable titled $message as follows : 我在名为$message的变量中有一个字符串,如下所示:

$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 ie TEST PRA in this case using PHP. 我只想在这种情况下使用PHP在锚标记(即TEST PRA)中获取文本。

How should I do this in an efficient way? 我应该如何有效地做到这一点? Can someone please help me in this regard? 有人可以在这方面帮助我吗?

Thanks in advance. 提前致谢。

Use preg_match_all function inorder to do a global match. 使用preg_match_all函数可以进行全局匹配。

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

Here preg_match would be enough. 在这里preg_match就足够了。 \\K discards the previously matched characters from printing at the final, so it won't consider the previouslly matched > character. \\K在最终打印时会丢弃先前匹配的字符,因此不会考虑先前匹配的>字符。 You could use a positive lookbehind instead of \\K also , like (?<=>) . 您也可以使用正向后视代替\\K ,例如(?<=>) [^<>]* 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 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM