preg_match - 结束标签和开始标签之间的文本

preg_match - text between closing and opening tag

我有很奇怪的任务要做。

我需要使用 PHP 中的 preg_match() 函数从 html 标签中获取文本。问题是我需要的文本是在关闭和打开 html 标签之间或者这个带标签的文本。

下面是我的 html 字符串:

<h2>Title of post</h2> 1 category <strong>task 1</strong> 1 category <strong>task 2</strong> 1 category <strong>task 3</strong>&nbsp; 

更具体地说:我需要 </h2><strong> 标签之间的字符串“1 类别”。

当我尝试在开始标签和结束标签之间抓取文本时 - 它工作正常,我正在使用此功能:

preg_match_all('#<strong>(.*?)</strong>#',$string,$matches);

我尝试了很多组合来获取结束标签和开始标签之间的文本。 None 他们成功了。我已经结束使用这样的功能:

preg_match_all('#<\/strong>(.*?)<strong>#',$content,$matches_all);

没有结果。

奇怪的是,在在线正则表达式测试器上,这个带有上述模式的函数有时会起作用。

我的图案不好吗?我错过了一些旗帜吗?您知道以这种方式获取文本的最佳方式是什么吗?不幸的是,我必须使用 Regex 方法,像 XMLDomParser 这样的解决方案在我的情况下是不允许的。

非常感谢您的帮助。

试试这个。

preg_match_all('/<([^>]+)>(?:([^<]+))*(?=[^>]*\<)/',$string,$matches);

Live Demo

您的 php installation/configuration 似乎有问题。

您的代码。

$content = '<h2>Title of post</h2> 1 category <strong>task 1</strong> 1 category <strong>task 2</strong> 1 category <strong>task 3</strong>&nbsp;'; 
preg_match_all('#<\/h2>(.*?)<strong>#',$content,$matches);
print_r($matches);

输出:

Array
(
    [0] => Array
        (
            [0] => </h2> 1 category <strong>
        )

    [1] => Array
        (
            [0] =>  1 category 
        )

)

直播demo

注意:由于您的模式只有一个匹配项(在 </h2> <strong> 之间),您可以像 $maches[1][0] 一样访问或使用preg_match.

如果您想要在结束标签和开始标签之间添加 所有 段文本,您可以使用此代码。请注意,我更改了您的文本,使每组 closing/opening 标签之间的文本不同,这样更明显的是匹配找到了每个值。

$str = '<h2>Title of post</h2> 1 category <strong>task 1</strong> 2 category <strong>task 2</strong> 3 category <strong>task 3</strong> ';
preg_match_all('#(?:</[^>]+>)(.*?)<#', $str, $matches);
print_r($matches[1]);

输出:

Array
(
    [0] =>  1 category 
    [1] =>  2 category 
    [2] =>  3 category 
)