PHP /正则表达式:如何获取HTML标签的字符串值? [英] PHP/regex: How to get the string value of HTML tag?

查看:388
本文介绍了PHP /正则表达式:如何获取HTML标签的字符串值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要正则表达式或 preg_match 的帮助,因为我我不是那么有经验的人,所以这里是我的问题。

I need help on regex or preg_match because I am not that experienced yet with regards to those so here is my problem.

我需要得到值get me,但我认为我的函数有错误。
html标签的数量是动态的。它可以包含许多嵌套的html标签,如粗体标签。

I need to get the value "get me" but I think my function has an error. The number of html tags are dynamic. It can contain many nested html tag like a bold tag. Also, the "get me" value is dynamic.

<?php
function getTextBetweenTags($string, $tagname) {
    $pattern = "/<$tagname>(.*?)<\/$tagname>/";
    preg_match($pattern, $string, $matches);
    return $matches[1];
}

$str = '<textformat leading="2"><p align="left"><font size="10">get me</font></p></textformat>';
$txt = getTextBetweenTags($str, "font");
echo $txt;
?>


推荐答案

<?php
function getTextBetweenTags($string, $tagname) {
    $pattern = "/<$tagname ?.*>(.*)<\/$tagname>/";
    preg_match($pattern, $string, $matches);
    return $matches[1];
}

$str = '<textformat leading="2"><p align="left"><font size="10">get me</font></p></textformat>';
$txt = getTextBetweenTags($str, "font");
echo $txt;
?>

这应该可以做到这一点

这篇关于PHP /正则表达式:如何获取HTML标签的字符串值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆