26

I want an if statement that uses same thingy like mysql something LIKE '%something%'

I want to build an if statement in php.

if ($something is like %$somethingother%) 

Is it possible?

The reason for me asking this question is that I don't want to change the MySQL command, it's a long page with many stuff on it, I don't want to build a different function for this.

Let me know if this is possible, if possible then how to do it .

11 Answers 11

39

if ($something is like %$somethingother%)

Is it possible?

no.

I don't want to change the MySQL command, it's a long page with many stuff on it

Use some good editor, that supports regular expressions in find & replace, and turn it to something like:

if(stripos($something, $somethingother) !== FALSE){ } 
Sign up to request clarification or add additional context in comments.

Comments

31

I know, this question isn't actual but I've solved similar problem :)

My solution:

/** * SQL Like operator in PHP. * Returns TRUE if match else FALSE. * @param string $pattern * @param string $subject * @return bool */ function like_match($pattern, $subject) { $pattern = str_replace('%', '.*', preg_quote($pattern, '/')); return (bool) preg_match("/^{$pattern}$/i", $subject); } 

Examples:

like_match('%uc%','Lucy'); //TRUE like_match('%cy', 'Lucy'); //TRUE like_match('lu%', 'Lucy'); //TRUE like_match('%lu', 'Lucy'); //FALSE like_match('cy%', 'Lucy'); //FALSE 

1 Comment

I like it - a small change. The pattern line should be $pattern = str_replace('%', '.*', preg_quote($pattern,'/'));. Otherwise forward slashes won't be escaped for preg_match().
5

look on strstr function

Comments

5

Use this function which works same like SQL LIKE operator but it will return boolean value and you can make your own condition with one more if statement

function like($str, $searchTerm) { $searchTerm = strtolower($searchTerm); $str = strtolower($str); $pos = strpos($str, $searchTerm); if ($pos === false) return false; else return true; } $found = like('Apple', 'app'); //returns true $notFound = like('Apple', 'lep'); //returns false if($found){ // This will execute only when the text is like the desired string } 

1 Comment

It doesn't work if the input is an array. I got error like: strtolower(): Argument #1 ($string) must be of type string. Please help. Thanks.
2

Use function, that search string in another string like: strstr, strpos, substr_count.

Comments

2

strpos() is not working for so i have to use this preg_match()

$a = 'How are you?'; if (preg_match('/\bare\b/', $a)) { echo 'true'; } 

like in this e.g i am matching with word "are" hope for someone it will be helpful

Comments

0

But you will have to give lowercase string then it will work fine. Example of strstr function:

$myString = "Hello, world!"; echo strstr( $myString, "wor" ); // Displays 'world!' echo ( strstr( $myString, "xyz" ) ? "Yes" : "No" ); // Displays 'No' 

Comments

0

If you have access to a MySQL server, send a query like this with MySQLi:

$SQL="select case when '$Value' like '$Pattern' then 'True' else 'False' end as Result"; $Result=$MySQLi->query($SQL)->fetch_all(MYSQLI_ASSOC)[0]['Result']; 

Result will be a string containing True or False. Let PHP do what it's good for and use SQL for likes.

2 Comments

I think he or she is only looking for a similar syntax or a trick in PHP to do the same thing than the sql 'like' keyword, but I'm not sure he/she is using a database for this.
Maybe someone doesn't have access to a SQL server, but it begs the question. If you are not using SQL why would you think of trying to mimic a SQL feature in PHP? PHP doesn't have like. It has the regular expression, which is better if you know how to use it, but there's the rub.
0

I came across this requirement recently and came up with this:

/** * Removes the diacritical marks from a string. * * Diacritical marks: {@link https://unicode-table.com/blocks/combining-diacritical-marks/} * * @param string $string The string from which to strip the diacritical marks. * @return string Stripped string. */ function stripDiacriticalMarks(string $string): string { return preg_replace('/[\x{0300}-\x{036f}]/u', '', \Normalizer::normalize($string , \Normalizer::FORM_KD)); } /** * Checks if the string $haystack is like $needle, $needle can contain '%' and '_' * characters which will behave as if used in a SQL LIKE condition. Character escaping * is supported with '\'. * * @param string $haystack The string to check if it is like $needle. * @param string $needle The string used to check if $haystack is like it. * @param bool $ai Whether to check likeness in an accent-insensitive manner. * @param bool $ci Whether to check likeness in a case-insensitive manner. * @return bool True if $haystack is like $needle, otherwise, false. */ function like(string $haystack, string $needle, bool $ai = true, bool $ci = true): bool { if ($ai) { $haystack = stripDiacriticalMarks($haystack); $needle = stripDiacriticalMarks($needle); } $needle = preg_quote($needle, '/'); $tokens = []; $needleLength = strlen($needle); for ($i = 0; $i < $needleLength;) { if ($needle[$i] === '\\') { $i += 2; if ($i < $needleLength) { if ($needle[$i] === '\\') { $tokens[] = '\\\\'; $i += 2; } else { $tokens[] = $needle[$i]; ++$i; } } else { $tokens[] = '\\\\'; } } else { switch ($needle[$i]) { case '_': $tokens[] = '.'; break; case '%': $tokens[] = '.*'; break; default: $tokens[] = $needle[$i]; break; } ++$i; } } return preg_match('/^' . implode($tokens) . '$/u' . ($ci ? 'i' : ''), $haystack) === 1; } /** * Escapes a string in a way that `UString::like` will match it as-is, thus '%' and '_' * would match a literal '%' and '_' respectively (and not behave as in a SQL LIKE * condition). * * @param string $str The string to escape. * @return string The escaped string. */ function escapeLike(string $str): string { return strtr($str, ['\\' => '\\\\', '%' => '\%', '_' => '\_']); } 

The code above is unicode aware to be able to catch cases like:

like('Hello 🙃', 'Hello _'); // true like('Hello 🙃', '_e%o__'); // true like('asdfas \\🙃H\\\\%🙃É\\l\\_🙃\\l\\o asdfasf', '%' . escapeLike('\\🙃h\\\\%🙃e\\l\\_🙃\\l\\o') . '%'); // true 

You can try all of this on https://3v4l.org/O9LX0

Comments

0

I think it's worth mentioning the str_contains() function available in PHP 8 which performs a case-sensitive check indicating whether a string is contained within another string, returning true or false.

Example taken from the documentation:

$string = 'The lazy fox jumped over the fence'; if (str_contains($string, 'lazy')) { echo "The string 'lazy' was found in the string\n"; } if (str_contains($string, 'Lazy')) { echo 'The string "Lazy" was found in the string'; } else { echo '"Lazy" was not found because the case does not match'; } //The above will output: //The string 'lazy' was found in the string //"Lazy" was not found because the case does not match 

See the full documentation here.

Comments

0

like_match() example is the best this one witch SQL reqest is simple (I used it before), but works slowly then like_match() and exost database server resources when you iterate by array keys and every round hit db server with request usually not necessery. I made it faster ferst cutting / shrink array by pattern elements but regexp on array works always faster. I like like_match() :)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.