How to check if there is a certain number in a php variable?

5

So I was giving a searched, looking for some function of php that verifies if a certain number exists inside a variable. And I found the preg_match ().

code:

$numeros = "1 2 3 4 5 6 7 8 9"; 
preg_match(1,$numeros);

Error:

  

Warning: preg_match(): Delimiter must not be alphanumeric or backslash

    
asked by anonymous 25.01.2017 / 13:51

3 answers

8

Use the delimiters inside the string you are looking for:

$numeros = "1 2 3 4 5 6 7 8 9"; 
preg_match('/1/',$numeros); // Você pode usar / ou #
    
25.01.2017 / 13:54
5

You can use strpos() . But it has to be regarded as string .

$numeros = "1 2 3 4 5 6 7 8 9"; 
$temNumero = strpos($numeros, '1');

if($temNumero >= 0) // ou ($temNumero > -1)
   echo 'Achou';
else 
   echo 'Não achou';

Or using preg_match_all() , in a regular expression.

$re = '/[1]/';
$str = '123456';

preg_match_all($re, $str, $matches);

if(count($matches) > 0)
   echo 'Achou';
else
   echo 'Não achou';
    
25.01.2017 / 13:53
5

Use strrpos or strrips if not returned falso was found:

int strrpos ( string $haystack , string $needle [, int $offset ] )

Example in your code:

<?php

    $numeros = "1 2 3 4 5 6 7 8 9"; 

    $result = strrpos ($numeros, "8");

    if (is_int($result))
    {
        echo 'encontrado';
    }
    else
    {
        echo 'não encontrou';
    }
    
25.01.2017 / 13:55