我想要一個if語句使用像mysql一樣的東西something LIKE '%something%'
PHP就像類似於MySQL的東西一樣,對於if語句?
我想在php中構建一個if語句。
if ($something is like %$somethingother%)
這可能嗎?
我問這個問題的原因是我不想更改MySQL命令,它是一個很長的頁面,上面有很多東西,我不想爲此構建不同的功能。
讓我知道這是否可能,如果可能的話,那麼該怎麼做。
我想要一個if語句使用像mysql一樣的東西something LIKE '%something%'
PHP就像類似於MySQL的東西一樣,對於if語句?
我想在php中構建一個if語句。
if ($something is like %$somethingother%)
這可能嗎?
我問這個問題的原因是我不想更改MySQL命令,它是一個很長的頁面,上面有很多東西,我不想爲此構建不同的功能。
讓我知道這是否可能,如果可能的話,那麼該怎麼做。
如果($東西就像%$ somethingother%)
這可能嗎?
沒有。
我不想改變MySQL命令,它是在它
使用一些很好的編輯器,支持查找&替換正則表達式有許多東西很長的網頁,並把它轉化爲是這樣的:
if(stripos($something, $somethingother) !== FALSE){
}
外觀上strstr功能
使用功能,像另一個字符串搜索字符串:strstr
,strpos
,substr_count
。
我知道,這個問題是不現實的,但我已經解決了類似的問題:)
我的解決辦法:
個/**
* 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);
}
例子:
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
我喜歡它 - 一個小小的變化。模式行應該是`$ pattern = str_replace('%','。*',preg_quote($ pattern,'/'));`。否則,對於preg_match(),正斜槓不會轉義。 – 2015-07-08 13:12:42
但是,你將不得不放棄小寫的字符串,那麼它會正常工作。 strstr功能的示例:
$myString = "Hello, world!";
echo strstr($myString, "wor"); // Displays 'world!'
echo (strstr($myString, "xyz") ? "Yes" : "No"); // Displays 'No'
strpos was perfect :) – friendishan 2011-02-06 08:27:43