如果您想使用正则表达式,请尝试以下操作:
/<b ?.*>(.*)<\/b>/
它将捕获 <b></b> 标签内的所有内容,包括标签本身。
Online Example
您可以使用简单的函数将上述正则表达式的用法扩展到不止一个 <b> 标记,并传递一个您想要捕获的标记:
例子:
function getTextBetweenTags($string, $tagname)
{
$pattern = '/<'.$tagname.'>.*?<\/'.$tagname.'>/is';
preg_match_all($pattern, $string, $matches);
return $matches;
}
用法:
$string = 'The <b>quick brown</b> fox jumps over the lazy dog \
The <b>quick black</b> fox jumps over the lazy dog \
The <b>quick white</b> fox jumps over the lazy dog';
$text = getTextBetweenTags($string, "b");
print_r($text);
输出:
Array
(
[0] => Array
(
[0] => <b>quick brown</b>
[1] => <b>quick black</b>
[2] => <b>quick white</b>
)
)
Online Example
编辑 1:
我已经为你扩展了上面的功能,所以它可以使用多个标签:
例子:
function getTextBetweenTags($string, $tagsname)
{
$tagsname = explode(',',$tagsname);
foreach ($tagsname as $tagname)
{
$pattern = '/<'.$tagname.'>.*?<\/'.$tagname.'>/is';
preg_match_all($pattern, $string, $matches);
$results[] = $matches;
}
return $results;
}
用法:
$string = 'The <b>quick brown</b> fox jumps <strong>over</strong> the lazy dog \
The <b>quick black</b> fox jumps over the <span>lazy</span> dog \
The <b>quick white</b> fox jumps over the lazy dog';
$text = getTextBetweenTags($string, "b,strong,span"); // Single or multiple HTML tags
print_r($text);
输出:
Array
(
[0] => Array
(
[0] => Array
(
[0] => <b>quick brown</b>
[1] => <b>quick black</b>
[2] => <b>quick white</b>
)
)
[1] => Array
(
[0] => Array
(
[0] => <strong>over</strong>
)
)
[2] => Array
(
[0] => Array
(
[0] => <span>lazy</span>
)
)
)
Online Example