I have a block of html stored in a custom field in wordpress. I need to return only the links from that custom field using a php function. It must be a function. Here is what i tried, but my result just says array:
<?php
function linkExtractor($html){
$linkArray = array();
if(preg_match_all('/<img\s+.*?src=[\"\']?([^\"\' >]*)[\"\']? [^>]*>/i',$html,$matches,PREG_SET_ORDER)){
foreach($matches as $match){
array_push($linkArray,array($match[1],$match[2]));
}
}
return $linkArray;
}
?>
Within wordpress i use it as a shortcode and it looks like. This is 100% the correct format as i use it all the time.
[linkExtractor(custom_field_name)]
Your result says array? Looks like you're trying to echo an array in which you'll just get the typeof data.
However, whatever is calling that function will have to loop through that array aswell. Anyways, clear up your post so I can understand it better. Thanks
And where is $matches? Also your function has no HTML param, nor isn't valid all together.
Btw I am not familiar with "Wordpress"
instead of using regex, try a proper html parser? for example, DOMDocument:
function linkExtractor(string $html): array {
$ret = array ();
$domd = @\DOMDocument::loadHTML ( $html );
foreach ( $domd->getElementsByTagName ( "*" ) as $ele ) {
if (! \method_exists ( $ele, 'getAttribute' )) {
// not all elements has getAttribute
continue;
}
$link = $ele->getAttribute ( "src" );
if (! is_string ( $link ) || strlen ( $link ) < 1) {
continue;
}
$ret [] = $link;
}
return $ret;
}