Check if a string contains a certain number

前端 未结 5 1933
死守一世寂寞
死守一世寂寞 2021-01-14 18:14

I have a string

8,7,13,14,16

Whats the easiest way to determine if a given number is present in that string?

$numberA = \"1         


        
相关标签:
5条回答
  • 2021-01-14 18:33

    Another way, that might be more efficient for laaaaaaaarge strings, is using a regexp:

    $numberA = "13";
    $string = "8,7,13,14,16";
    
    if(preg_match('/(^|,)'.$numberA.'($|,)/', $string)){
        $result = "Yeah, that number is in there";
    } else {
        $result = "Sorry.";
    }
    
    0 讨论(0)
  • 2021-01-14 18:35

    Make sure you match the full number in the string, not just part of it.

    function numberInList($num, $list) {
        return preg_match("/\b$num\b/", $list);
    }
    $string = "8,7,13,14,16";    
    numberInList(13, $string); # returns 1
    numberInList(8, $string); # returns 1
    numberInList(1, $string); # returns 0
    numberInList(3, $string); # returns 0
    
    0 讨论(0)
  • 2021-01-14 18:37
    <?php 
    in_array('13', explode(',', '8,7,13,14,16'));
    ?>
    

    …will return whether '13' is in the string.

    Just to elaborate: explode turns the string into an array, splitting it at each ',' in this case. Then, in_array checks if the string '13' is in the resulting array somewhere.

    0 讨论(0)
  • 2021-01-14 18:50
    if (strpos(','.$string.',' , ','.$numberA.',') !== FALSE) {
        //found
    }
    

    Notice guard ',' chars, they will help to deal with '13' magic '1, 2, 133' case.

    0 讨论(0)
  • 2021-01-14 18:51

    A simple string search should do if you are just checking to find existence of the string. I dont speak php but i think this is how it could be done.

    $mystring = '8,7,13,14,16';
    $findme   = '13';
    
    if (preg_match('/(?>(^|[^0-9])'.$findme.'([^0-9]|$))/', $mystring)) {
        $result = "Yeah, that number is in there";
    } else {
        $result = "Sorry.";
    }
    
    0 讨论(0)
提交回复
热议问题