Search code examples
phpstringstrpos

How to use conditions on functions like strpos() in PHP?


I wanted to check if a string contains specific words? According How do I check if a string contains a specific word? I can use strpos() function.

Sample Code I wrote

if(strpos($value, 'filters(10)') === false){
    //Do something
} else {
    //Do Another Thing
}

If I need to check specific word filters(10) above functions works fine. But I need to check all numbers above 10 with filter word.

Example

$value = 'bla bla  bla bla' // Should return false
$value = 'bla bla filters(1) bla bla' // Should return false
$value = 'bla bla filters(5) bla bla' // Should return false
$value = 'bla bla filters(10) bla bla' // Should return true
$value = 'bla bla filters(15) bla bla' // Should return true
$value = 'bla bla filters(20) bla bla' // Should return true

How to modify my code to get above results?


Solution

  • Here you can use Regex for getting that particular no. and then apply further conditions.

    Regex: filters\((\d+)\)

    This will match filters( and then capture digits and then )

    Try this code snippet here

    preg_match("#filters\((\d+)\)#", $value, $matches);
    if(isset($matches[1]) && $matches[1]>10)
    {
        //do something on true
    }
    else
    {
        //do something on false
    }