2017-01-17 157 views
2

我有這個字符串:檢查是否字符串包含任何文本

$mystring = "SIZE,DETAIL"; 

而且I'm使用:

@if (strpos($mystring, 'SIZE')) 
     {{ $item->size }} 
@endif 
@if (strpos($mystring, 'DETAIL')) 
     {{ $item->detail }} 
@endif 

但這個工作正常大小,但不與細節。

這裏有什麼問題?

+0

也許嘗試http://php.net/manual/en/function.preg-match.php - 和至極Laravel版本你真的使用? –

回答

1

這個函數可以返回布爾FALSE ,但也可能返回一個非布爾值,其值爲FALSE。

試試這個:

@if (strpos($mystring, 'SIZE') !== false) 
    {{ $item->size }} 
@endif 
@if (strpos($mystring, 'DETAIL') !== false) 
    {{ $item->detail }} 
@endif 

參考:http://php.net/manual/en/function.strpos.php

+1

由'非布爾值,其計算結果爲false'他的意思是0,當您搜索的字符串在位置0處開始時發生0 – Cashbee

+0

此函數可能會返回布爾型FALSE,但也可能會返回一個非布爾值,其值爲FALSE 。有關更多信息,請閱讀布爾部分。使用===運算符來測試此函數的返回值。請參考:http://php.net/manual/en/function.strpos.php – mith

+0

我剛剛意識到,雖然它對'大小'起作用是沒有意義的,但是它對'細節'起作用。它應該反之亦然:) – Cashbee

-1

使用strpos時,您需要將其與FALSE進行比較。的刀片代碼的一個例子是:

@if (strpos($mystring, 'SIZE') !== FALSE) 
     {{ $item->size }} 
@endif 
@if (strpos($mystring, 'DETAIL') !== FALSE) 
     {{ $item->detail }} 
@endif 

然而,在使用Laravel的時候,你可以用str_contains($haystack, $needles)而不是strpos

3

由於您使用Laravel,您可以使用str_contains()幫手:

@if (str_contains($mystring, 'SIZE')) 

str_contains函數確定給定的字符串包含給定的值

相關問題