I am learning PHP. I have to extract all the script tags
of a particluar $url
whose src
contain a particular word say 'abc'
.
I have tried this:
$domd = new DOMDocument();
@$domd->loadHTML(@file_get_contents($url));
$data = array();
$items = $domd->getElementsByTagName('script');
foreach($items as $item) {
if($item->hasAttribute('src')){
$data[] = array(
'src' => $item->getAttribute('src')
);
}
}
print_r($data);
echo "
";
The above code gives me the list of all the script tag's src's
present in the $url
.
But how should i check if a src
in a script tag contains a word 'abc'
?
If you need to check each value in the array, to see if it contains 'abc'
, try a foreach()
loop with an if statement using strpos()
to see if the value contains 'abc'
, and then do something with it.
Something like this should do the trick:
foreach( $data as $key=>$value ) {
if( strpos( $value['src'],'abc' ) !== false ) {
//do something with it here
}
}
Just edited this. Call the ['src']
element of the subArray
and use that in strpos()
. Alternately, you could change your line that builds the $data
array to this, since you only have one element in each subArray
:
if($item->hasAttribute('src')){
$data[] = $item->getAttribute('src');
}