【问题标题】:Extract text from specific HTML tag [duplicate]从特定的 HTML 标记中提取文本 [重复]
【发布时间】:2019-07-29 01:00:07
【问题描述】:

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

现在我有了这个 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

【问题讨论】:

  • 不要使用正则表达式使用HTML/DOM解析器解析HTML
  • 如何获得链接?它们是由 PHP 生成的吗?发布更多代码以获得更好的解决方案

标签: php html regex


【解决方案1】:

您可以编写一个简单的正则表达式来匹配包含指向select-admin-domain.do 的链接的&lt;a&gt; 标记

例如:

$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"
//    }

【讨论】:

  • 不使用array_column,去掉preg_match_all的最后两个参数,结果在$matches[1]
【解决方案2】:

如果您的 $string var a (string) 包含一个 html 代码,并且您想要获取每个链接的 href 或文本,您也可以使用此代码:

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

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

【讨论】:

    猜你喜欢
    • 2018-02-15
    • 2012-06-12
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2012-08-31
    • 2019-05-19
    相关资源
    最近更新 更多