Search code examples
phpreturnpreg-match

if preg_match finds nothing echo something


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>

Solution

  • 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.