提取字符串中的li文本值

时间:2018-07-09 09:43:08

标签: php mysqli

我尝试了许多功能,但无法获得确切的值。这是我的动态文字。我只想获取/提取“大小”值(36、38、40,...)。我如何从此文本值中提取?这是我从数据库中获得的全部内容。

<ul>
<li>
<span>Colors: </span>Off White, Turquoise</li>
<li><span>Type: </span>Stitched</li>
<li><span>Sizes: </span>36, 38, 40</li>
</ul>

2 个答案:

答案 0 :(得分:0)

如果要直接提取数据会很困难,最好将其转换为数组,然后循环遍历该数组以获取所需的值。

<?php 
$html = '<li> <a href="link1"> 36 </a> <li>
<li> <a href="link2"> 38 </a> <li>
<li> <a href="link3"> 40 </a> <li>
';

// Create a new DOM Document
$xml = new DOMDocument();

// Load the html contents into the DOM
$xml->loadHTML($html);

// Empty array to hold all links to return
$result = array();

//Loop through each <li> tag in the dom
foreach($xml->getElementsByTagName('li') as $li) {
    //Loop through each <a> tag within the li, then extract the node value
    foreach($li->getElementsByTagName('a') as $links){
    //if result equal expected number then do the logic
    }
}
//Return the links
print_r($result);
/*
Array
(
    [0] =>  36 
    [1] =>  38 
    [2] =>  40 
)

*/
?>

答案 1 :(得分:0)

您想要实现的目标无法用纯PHP来完成,但是在javascript中则可以实现,因为js是一种面向DOM操作的语言。这是示例线程,要求您提供类似的内容:

Get the text of an li element