Question

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.

Was it helpful?

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';
}

OTHER TIPS

at a minimum, you need to do this:

<?php
$data['id="test"'] = 'A';
$data=array_keys($data);
$data = preg_quote($data[0],"'");

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

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

However.. there are many ways this could be optimized, if you are willing/able to refactor the structure of $data

also note that this will only look for an exact match. It will not match if "test" is wrapped in single quotes, or if there are spaces between id and "test" etc..

in short, the way you have it now, you may as well just use strpos

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top