![](/img/trans.png)
[英]find all words that begin with @ and that contain all chars except for spaces in regex
[英]Filter and stristr(): find all the words except the first
在過濾將要顯示的項目時,如果我要搜索的單詞是該項目的第一個單詞,則不會找到它。 示例:我的標題是“ 明天將是晴天 ”。 如果我尋找明天 ,則找不到,如果我尋找晴天或白天 ,則找到。 如何搜索整個單詞,包括第一個單詞? 這是代碼:
$url_noticias = 'storage/json/es/noticia.json';
$noticias = json_decode(file_get_contents($url_noticias), true);
$noticias = array_filter($noticias);
$data['noticias'] = collect($noticias)->filter(function ($item) use ($request){
return stristr($item['title'], $request->texto, true);
});
<?php
$haystack = 'Tomorrow will be a sunny day';
$needles = ['tomorrow', 'foo', 'sunny', 'day'];
foreach($needles as $needle) {
if (stristr($haystack, $needle) !== false)
printf ("'%s' found in '%s'\n", $needle, $haystack);
else
printf("'%s' not found in '%s'\n", $needle, $haystack);
}
輸出:
'tomorrow' found in 'Tomorrow will be a sunny day'
'foo' not found in 'Tomorrow will be a sunny day'
'sunny' found in 'Tomorrow will be a sunny day'
'day' found in 'Tomorrow will be a sunny day'
顯然這可能是將0(零)視為假的問題。
如果字符串在第一個位置,即。 位置0並且測試是否找到,則零值解釋為false。 但是在這種情況下,可以在零位置成功找到它。
為了避免這種行為,不要只比較值,也不要比較類型。
(0 == false) -> true
但
(0 === false) -> false
所以測試的發生應該像($position !== false)
返回布爾值而不是位置:
return (stristr($item['title'], $request->texto, true) !== false) ? true : false;
編輯
正如@Progrock正確指出的那樣,函數stristr
不返回位置,而是返回子字符串或false。
因此,在字符串開頭找不到單詞的根本原因是其他地方。
stristr
函數stristr
不區分大小寫的搜索,如果找到了string,並且找到了tommorow ,則返回的值是string
。 並且該字符串被視為true ,因此比較工作如下:
("string" == false) -> false
但是,使用設置為true
的第三個可選參數調用stristr
。 根據文檔 , stristr
函數會在第一次出現針(不包括針)之前返回干草堆的一部分。
並且由於明天是字符串的開頭, 明天將是晴天,因此返回的值為空字符串,該字符串將被解釋為false:
("" == false) -> true
結論
如果將第三個參數保留為true
,則在字符串的開頭出現單詞空字符串的問題,如果將其設置為false
或將其刪除(它是默認值為false的可選參數),則單詞返回的空字符串會出現問題在字符串的末尾。
因此,無論使用true / false作為第三個參數,原始答案中提出的解決方案都可以處理這兩種情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.