使用正则表达式从PHP中的标记中获取值

时间:2022-06-01 20:37:49

Using regex in PHP how can I get the 108 from this tag?

在PHP中使用正则表达式如何从此标记中获取108?

<td class="registration">108</td>

2 个解决方案

#1


4  

Regex isn't a good solution for parsing HTML. Use a DOM Parser instead:

正则表达式不是解析HTML的好方法。改为使用DOM解析器:

$str = '<td class="registration">108</td>';    
$dom = new DOMDocument();
$dom->loadHTML($str);      

$tds = $dom->getElementsByTagName('td');
foreach($tds as $td) { 
    echo $td->nodeValue; 
}

Output:

输出:

108

Demo!

演示!

The above code loads up your HTML string using loadHTML() method, finds all the the <td> tags, loops through the tags, and then echoes the node value.

上面的代码使用loadHTML()方法加载HTML字符串,查找所有标记,遍历标记,然后回显节点值。


If you want to get only the specific class name, you can use an XPath:

如果只想获取特定的类名,可以使用XPath:

$dom = new DOMDocument();
$dom->loadHTML($str);      

$xpath = new DomXPath($dom);

// get the td tag with 'registration' class
$tds = $xpath->query("//*[contains(@class, 'registration')]");

foreach($tds as $td) { 
    echo $td->nodeValue;
}

Demo!

演示!

This is similar to the above code, except that it uses XPath to find the required tag. You can find more information about XPaths in the PHP manual documentation. This post should get you started.

这与上面的代码类似,只是它使用XPath来查找所需的标记。您可以在PHP手册文档中找到有关XPath的更多信息。这篇文章应该让你开始。

#2


-1  

If you wish to force regex, use the <td class=["']?registration["']?>(.*)</td> expression

如果你想强制正则表达式,使用(。*) 表达式

#1


4  

Regex isn't a good solution for parsing HTML. Use a DOM Parser instead:

正则表达式不是解析HTML的好方法。改为使用DOM解析器:

$str = '<td class="registration">108</td>';    
$dom = new DOMDocument();
$dom->loadHTML($str);      

$tds = $dom->getElementsByTagName('td');
foreach($tds as $td) { 
    echo $td->nodeValue; 
}

Output:

输出:

108

Demo!

演示!

The above code loads up your HTML string using loadHTML() method, finds all the the <td> tags, loops through the tags, and then echoes the node value.

上面的代码使用loadHTML()方法加载HTML字符串,查找所有标记,遍历标记,然后回显节点值。


If you want to get only the specific class name, you can use an XPath:

如果只想获取特定的类名,可以使用XPath:

$dom = new DOMDocument();
$dom->loadHTML($str);      

$xpath = new DomXPath($dom);

// get the td tag with 'registration' class
$tds = $xpath->query("//*[contains(@class, 'registration')]");

foreach($tds as $td) { 
    echo $td->nodeValue;
}

Demo!

演示!

This is similar to the above code, except that it uses XPath to find the required tag. You can find more information about XPaths in the PHP manual documentation. This post should get you started.

这与上面的代码类似,只是它使用XPath来查找所需的标记。您可以在PHP手册文档中找到有关XPath的更多信息。这篇文章应该让你开始。

#2


-1  

If you wish to force regex, use the <td class=["']?registration["']?>(.*)</td> expression

如果你想强制正则表达式,使用(。*) 表达式