Search code examples
phppreg-matchfile-get-contentsarray-key

PHP: searching id tags @ .html file


I have this simple code I want to search some tags on a .html file but I get some error I'm just new to php and I encounter 'preg_match' command.

here's my simple code:

<?php
$data['id="test"'] = 'A';

$html = file_get_contents('test.html');

if(preg_match(array_keys($data), $html)) 
{
    echo 'FOUND';
}
else
{
    echo 'NOT FOUND';
}
?>

it gives me an error Warning: preg_match() expects parameter 1 to be string, array given in

the code above searches in test.html if "id=test" test exist in the test.html file.


Solution

  • you can see that the preg_match needs the first parameter to be a string

    int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )
    

    and that array_keys return value is "array"

    array array_keys ( array $array [, mixed $search_value = NULL [, bool $strict = false ]] )
    

    so you get "preg_match() expects parameter 1 to be string, array given"

    try this :

    $data[] = 'id="test"';
    $data[] = 'id="test2"';
    $data[] = 'id="test3"';
    $html = file_get_contents('test.html');
    foreach ($data as $search){
     if (strpos($html , $search) !== FALSE)
        echo 'FOUND';
     else
        echo 'NOT FOUND';
    }