检查标签 &使用 PHP 获取标签内的值 [英] Check tag & get the value inside tag using PHP

查看:24
本文介绍了检查标签 &使用 PHP 获取标签内的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直很困惑.所以这是我的问题,我有这样的文字:

I've been confused. So here's my problem, I have a text like this :

<ORGANIZATION>Head of Pekalongan Regency</ORGANIZATION>, Dra. Hj.. Siti Qomariyah , MA and her staff were greeted by <ORGANIZATION>Rector of IPB</ORGANIZATION> Prof. Dr. Ir. H. Herry Suhardiyanto , M.Sc. and <ORGANIZATION>officials of IPB</ORGANIZATION> in the guest room.

我正在尝试使用我的代码获取 <ORGANIZATION> 标签内的值:

I'm try to get the value inside <ORGANIZATION> tag using my code :

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

但是当有 3 个标签 时,此代码仅从最后一个标签(IPB 官员)中检索一个值.

But this code only retrieve one value from the last tag (officials of IPB) when there are 3 tags <ORGANIZATION>.

现在,我不知道修改此代码以获取标签内的所有值而不会重复.所以请帮忙,提前致谢.:D

Now, I don't have idea to modify this code to get all value inside tag without duplication. So please help, thanks in advance. :D

推荐答案

preg_match 只会返回第一个匹配项,如果出现以下情况,您当前的代码将失败:

preg_match will only return the first match, and your current code will fail if:

  • 标签的大写方式不同
  • 标签的内容多于一行
  • 同一行中有多个标签.

相反,试试这个:

function get_text_between_tags($string, $tagname) {
    $pattern = "/<$tagname\b[^>]*>(.*?)<\/$tagname>/is";
    preg_match_all($pattern, $string, $matches);
    if(!empty($matches[1]))
        return $matches[1];
    return array();
}

这是可以接受的使用正则表达式进行解析,因为这是一个明确定义的情况.但是请注意,无论出于何种原因,如果标签的属性值中有 > ,它就会失败.

This is acceptable use of regexes for parsing, because it is a clearly-defined case. Note however that it will fail if, for whatever reason, there is a > inside an attribute value of the tag.

如果您想避免愤怒小马,试试这个:

If you prefer to avoid the wrath of the pony, try this:

function get_text_between_tags($string, $tagname) {
    $dom = new DOMDocument();
    $dom->loadHTML($string);
    $tags = $dom->getElementsByTagName($tagname);
    $out = array();
    $length = $tags->length;
    for( $i=0; $i<$length; $i++) $out[] = $tags->item($i)->nodeValue;
    return $out;
}

这篇关于检查标签 &amp;使用 PHP 获取标签内的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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