Equivalent to PHP LIKE

Asked

Viewed 6,678 times

5

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

"PARA" would equal "PARALLEL", "PARALLAX", "PARALLELEPIPED", "PARAMETER" ...
because it has the same beginning.


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

  • "equal" or "has"?

3 answers

10


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)

6

You can use the function strpos which is used to find the occurrence of one 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 on Soen

4

You can use the function str_pos

For example:

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

Browser other questions tagged

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