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

Asked

Viewed 2,397 times

5

So I was doing a search, looking for some php function that checks if a certain number exists within a variable. And I found the preg_match(). Only that has a however, php gives an error and so I intended it does not work with numbers only with other characters someone can help me?

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

  • you need to use the delimiters...

  • 2

    The following functions worked. many thanks.

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 #

5

One can use the strpos(). But it has to be looked at 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';
  • 2

    The first solution has many limitations, mainly because the function strpos will return 0 to number 1 and when tested on if, the test will fail.

  • Corrected by Anderson. Thanks.

4

Utilize strrpos or strripos if you don’t return 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';
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.