Php 从数组中删除空/空元素/索引/键
我将从HTMl内容中分离所有url链接 使用此代码Php 从数组中删除空/空元素/索引/键,php,arrays,dom,Php,Arrays,Dom,我将从HTMl内容中分离所有url链接 使用此代码 $doc = new DOMDocument(); $doc->loadHTML($string); $anchorTags = $doc->getElementsByTagName('a'); $links = array(); foreach ($anchorTags as $url) { $source = parse_url($url->getAttribute('href')); $source =
$doc = new DOMDocument();
$doc->loadHTML($string);
$anchorTags = $doc->getElementsByTagName('a');
$links = array();
foreach ($anchorTags as $url) {
$source = parse_url($url->getAttribute('href'));
$source = preg_replace('/^www\./', '', $source['host']);
$links[$source][$url->getAttribute('href')] = $url->nodeValue;
}
使用上述代码输出。
Array
(
[Facebook] => Array
(
[facebook.com] => https://www.facebook.com/
)
[Google] => Array
(
[google.com] => https://www.google.com/
)
[] => Array
(
[] =>
)
[yahoo] => Array
(
[yahoo.com] => https://www.yahoo.com/
)
)
我只想从数组中删除空/空元素/索引/键
为此,我正在使用
但没有得到解决方案
print_r(array_filter($links));
或者,更优雅一点,如果数组为空,甚至不要将结果推送到数组中:
if ($source != "") $links[$source][$url->getAttribute('href')] = $url->nodeValue;
或者,更优雅一点,如果数组为空,甚至不要将结果推送到数组中:
if ($source != "") $links[$source][$url->getAttribute('href')] = $url->nodeValue;
你可以像这样检查斯特伦
print_r(数组过滤器($links,'strlen')代码>你可以像这样查看strlen
print_r(数组过滤器($links,'strlen')代码>只需添加检查值的条件:
$links = array();
foreach ($anchorTags as $url) {
$source = parse_url($url->getAttribute('href'));
$source = preg_replace('/^www\./', '', $source['host']);
if($source != null && $source != "" && $url->nodeValue != null && $url->nodeValue != ""){
$links[$source][$url->getAttribute('href')] = $url->nodeValue;
}
}
只需添加检查值的条件:
$links = array();
foreach ($anchorTags as $url) {
$source = parse_url($url->getAttribute('href'));
$source = preg_replace('/^www\./', '', $source['host']);
if($source != null && $source != "" && $url->nodeValue != null && $url->nodeValue != ""){
$links[$source][$url->getAttribute('href')] = $url->nodeValue;
}
}
你可以试试这个
// Remove empty elements
foreach($links as $key => $val){
if($val == '')
{
unset($val);
}
}
你可以试试这个
// Remove empty elements
foreach($links as $key => $val){
if($val == '')
{
unset($val);
}
}