从特定的HTML标签提取文本

时间:2019-07-29 01:00:07

标签: php html regex

我正在编写小脚本,但遇到了这个问题

现在我有了这个HTML代码

<div class="domains">
							<ul>
		<li class="noMessages">
<a href="select-admin-domain.do?domain=ex1.com">ex1.com</a>
										</li>
<li class="noMessages">
<a href="select-admin-domain.do?domain=ex2.com">ex2.com</a>
						</li>
<li class="cpCurrentDomain noMessages">
<a href="select-admin-domain.do?domain=ex3.com">ex3.com</a>
						</li>
<li class="noMessages">
<a href="select-admin-domain.do?domain=ex4.com">ex4.com</a>
										</li>
								
							</ul>
						</div>
现在我想使用PHP

从所有这些html标记中提取文本
<a href="select-admin-domain.do?domain=ex1.com">ex1.com</a>
<a href="select-admin-domain.do?domain=ex2.com">ex2.com</a>
<a href="select-admin-domain.do?domain=ex3.com">ex3.com</a>
<a href="select-admin-domain.do?domain=ex4.com">ex4.com</a>

所以输出变成 ex1.com ex2.com 等。

我已经编写了这段代码

<?php
function GetStr($string,$start,$end){
    
        
    
    $str = explode($start, $string);
    $str = explode($end, $str[1]);
    echo $str[0];
    
    
}
$ss= getStr($htmlcode,'<a href="select-admin-domain.do?domain=','">');

echo $ss;

效果很好,但只给我第一输出 ex1.com 我想回声所有这些,而不仅仅是1

2 个答案:

答案 0 :(得分:1)

您可以编写一个简单的正则表达式来匹配包含到<a>的链接的select-admin-domain.do标签

例如:

$re = '/<a href="select-admin-domain.do.*?">(.*?)<\/a>/';
if (preg_match_all($re, $html, $matches, PREG_SET_ORDER, 0)) {
    var_dump(array_column($matches, 1));
}

// Outputs
//    array(4) {
//        [0] =>
//      string(7) "ex1.com"
//        [1] =>
//      string(7) "ex2.com"
//        [2] =>
//      string(7) "ex3.com"
//        [3] =>
//      string(7) "ex4.com"
//    }

答案 1 :(得分:0)

如果您的$string变量中有一个(string)包含html代码,并且您希望获得每个链接的href或文本,也可以使用此代码:

//$string var containt html
echo strip_tags($string);

//output
ex1.com ex2.com ex3.com ex4.com