0

This is my code:

function getaname($name)
{
    $result = file_get_contents('https://www.something.com');
    $regex = '/<div class="classname">([^<]*)<\/div>/';
    if (preg_match($regex, $result, $matches)) {   
        return $matches[1]; 
    } else{
        return 'N/A';}
}

This code is working perfectly when preg_match finds something in the div but I want it to echo or return N/A when it finds nothing like in the dive

<div></div>
  • 1
    Do you have quotes round `N/A`? – Nigel Ren Sep 29 '19 at 14:23
  • Side note, it would be a little cleaner if the function's execution was consistent, meaning that it would be better to return `false` or `NULL` instead of doing an `echo`. You are probably checking after the fact that the value returned is an array anyway so you may as well just echo in response to the return. – Rasclatt Sep 29 '19 at 14:27
  • Well i can keep N/A in my text so if it finds nothing it doesn't return the empty div but it does ... what I want is that: if the preg_match find 0 caractere in the div it returns nothing , so the original text which is N/A stays and doesn't desepear like it does now – Nacereddine Allal Sep 29 '19 at 14:36

1 Answers1

0

I suppose you don't explain the conditions exactly, I suppose you check for empty div which in your case is <div class="classname"></div>.

In this case your regexp still finds occurence of <div class="classname"> and preg_match returns truthy value. So, in this case you also need to check that $matches[1] is not empty:

if (preg_match($regex, $result, $matches) && !empty($matches[1])) {
    return $matches[1]; 
} else {
    return 'N/A';
}

Here's a fiddle https://3v4l.org/XUvUD, uncomment $result lines and see the output in each case.

Or your regexp can be chaged to $regex = '/<div class="classname">([^<]+)<\/div>/';, see plus instead of *, which means "at least one symbol". In this case the rest of the code should not be changed. Again fiddle here https://3v4l.org/Eo1bF.

u_mulder
  • 54,101
  • 5
  • 48
  • 64