fri*_*han 12 php mysql if-statement
我想要一个使用像mysql一样的if语句 something LIKE '%something%'
我想在php中构建一个if语句.
if ($something is like %$somethingother%)
Run Code Online (Sandbox Code Playgroud)
可能吗?
我问这个问题的原因是我不想改变MySQL命令,它是一个包含很多东西的长页面,我不想为此构建不同的函数.
如果可能的话,请告诉我,如果可能的话,如何做到这一点.
dev*_*ler 27
if($ something就像%$ somethingother%)
可能吗?
没有.
我不想改变MySQL命令,它是一个包含许多内容的长页面
使用一些好的编辑器,它支持查找和替换中的正则表达式,并将其转换为:
if(stripos($something, $somethingother) !== FALSE){
}
Run Code Online (Sandbox Code Playgroud)
Pet*_*yík 18
我知道,这个问题不是实际的,但我已经解决了类似的问题:)
我的解决方案
/**
* 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);
}
Run Code Online (Sandbox Code Playgroud)
例子:
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
Run Code Online (Sandbox Code Playgroud)
使用此函数,其工作方式与 SQL LIKE运算符相同,但它将返回布尔值,并且您可以使用另一个 if 语句创建自己的条件
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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
57242 次 |
| 最近记录: |