Equivalent to LIKE in PHP

5

How do I compare two strings in PHP in the same way as LIKE in mysql. For example:

"PARA" would be equal to "PARALLEL", "PARALLAX", "PARALLELEPIPEDO", "PARAMETER" ...
because it has the same start.


But regardless of form, I would like to make LIKE identical.

    
asked by anonymous 19.11.2015 / 18:33

3 answers

9

You can use regular expressions to emulate the behavior of LIKE in PHP:

<?php

function like($needle, $haystack)
{
    $regex = '/' . str_replace('%', '.*?', $needle) . '/';

    return preg_match($regex, $haystack) > 0;
}

var_dump(like('rod%', 'rodrigorigotti'));   // bool(true)
var_dump(like('%tti', 'rodrigorigotti'));   // bool(true)
var_dump(like('%gori%', 'rodrigorigotti')); // bool(true)
var_dump(like('%lala', 'rodrigorigotti'));  // bool(false)
var_dump(like('lala%', 'rodrigorigotti'));  // bool(false)
var_dump(like('%lala%', 'rodrigorigotti')); // bool(false)
    
19.11.2015 / 18:45
5

You can use the strpos function that is used to find the occurrence of a string within another

$valor = "PARALELEPIPEDO";
if (strpos($valor,"PARA") !== false) {
    echo "Encontrou";
}

Using regular expressions - preg_match

if(preg_match("/PARA/", $valor) {
    echo "Encontrou";
}

Using substr_count

if (substr_count($valor, 'PARA') > 0) {
    echo "Encontrou";
}

Similar question in SOen

19.11.2015 / 18:38
4

You can use the str_pos function

For example:

if ( strpos("paralelepipedo", "para") !== -1 ){
    //seu código aqui
}
    
19.11.2015 / 18:39