【问题标题】:Search php string - %like% sql搜索 php 字符串 - %like% sql
【发布时间】:2014-08-12 12:45:51
【问题描述】:

现在我使用stristr($q, $string) 但如果

$string = "one monkey can jump 66 times";
$q = "monkey 66";

我想知道这个字符串是否同时包含monkey 和66。

我该怎么做?

【问题讨论】:

  • 你想在两个字符串中搜索相似的词吗??

标签: php string search


【解决方案1】:

您可以同时使用stristr 和strpos。

正如post 中所报告的,第二种方法速度更快,内存占用更少。

好吧,看看这几行:

// here there are your string and your keywords
$string = "one monkey can jump 66 times";
$q = "monkey 66";

// initializate an array from keywords in $q
$q = explode(" ", $q);

// for every keyword you entered
foreach($q as $value) {

// if strpos finds the value on the string and return true
if (strpos($string, $value)) 

    // add the found value to a new array 
    $found[] = $value;

}

// if all the values are found and therefore added to the array,
// the new array should match the same object of the values array    
if ($found === $q) {

    // let's go through your path, super-man!
    echo "ok, all q values are in string var, you can continue...";

}

【讨论】:

  • if ($found === $q) { // 让我们走你的路吧,超人! echo "ok,所有 q 值都在字符串 var 中,你可以继续..."; } 它是一个数组,你不能将它与 $q 或?
  • $q 在我们分解时变成了一个数组: $q = explode(" ", $q);所以 === 检查两个对象是否相同
【解决方案2】:
if(stristr('monkey', $string) && stristr('66', $string)) {
    //Do stuff
}

【讨论】:

  • 好吧,那行不通。我使用 ajax 从文本输入中发送变量。因此,如果我想知道字符串是否同时包含“monkey”和“66”,我必须先将 $q 分解为一个数组。
  • 有什么不好的?请更明确。
  • @AndersNilsson 如果你已经知道必须炸掉它,为什么还要问?
【解决方案3】:

通过给他们一个变量 $monkey,$value ($monkey jumps $value) 来简单地发布你的变量值,然后获取它的值

【讨论】:

  • 这是一个非常.. 非常漫长的过程,网站的功能会因输入量而严重下降
  • 不,它可以简单地通过 ajax 来实现,只需通过给定的 id 发布值并通过另一个值 +(添加)它,然后只需通过数据流发布它
【解决方案4】:

您可以使用strpos() 函数来查找一个字符串在另一个字符串中的出现:

$a = 'How are you?';

if (strpos($a, 'are') !== false) {
    echo 'true';
}

请注意,使用!== false 是故意的(!= false 和=== true 都不起作用); strpos() 返回针字符串在 haystack 字符串中开始的偏移量,如果未找到针,则返回布尔值 false。由于 0 是一个有效的偏移量,而 0 是“错误的”,我们不能使用像 !strpos($a, 'are') 这样更简单的构造。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-24
    • 1970-01-01
    • 2011-02-05
    • 1970-01-01
    相关资源
    最近更新 更多