strpos() == '' 未能在字符串开头找到匹配项[重复]

问题描述 投票:0回答:3

ScreenShot

它适用于所有逗号分隔值,但不适用于

Restaurant
。 请建议我应该做什么。

$service = "Restaurant,24x7_room_service,Parking,currency_exchange,deposite_boxes,Laundry,pool,gym,AC,TV,Fridge,Intercom,Intercom,Extra Bed (if needed Chargeable)";
                            
//$dservices = str_ireplace(',', ' ', $d['services']);
$dservices = "Restaurant,24x7_room_service,Parking,currency_exchange,deposite_boxes,Laundry,pool,gym,AC,TV";
$loop = explode(",", $service);
                            
foreach ($loop as $action)
{
    ?>
    <li style="width:50%; float:left; padding: m10px;">
        <?php  
        if (strpos($dservices, $action) == '') {
            echo '<i style="color:red;" class="fa fa-times-circle"></i>';
        } else {
            ?><i style="color:#004386;" class="fa fa-check-circle"></i><?php
        }
        ?>
        <?= $action ?>
    </li>
    <?php
}
?>
php strpos
3个回答
2
投票

将 if 条件替换为以下内容:

if(strpos($dservices, $action) === false)

0
投票

因为您的餐厅位于 0 位置,对于场景而言,存在,但返回值 0 使您的

if
条件为假。

更改了这行代码

if(strpos($dservices,$action)=='') 

if(strpos($dservices,$action)=== false) 

这将检查位置编号,如果不存在则返回负值。


0
投票

更好的方法是将

$dservices
分解为另一个数组,而不是使用
strpos

$dservices_array = array_flip(explode(',', $dservices));
foreach ($loop as $action) {
    ?>
    <li style="width:50%;float:left;padding: 10px;">
    <?php  
    if(!isset($dservices_array[$action])) { 
        echo '<i style="color:red;" class="fa fa-times-circle"></i>';
    } else { 
        echo '<i style="color:#004386;" class="fa fa-check-circle"></i>';
    }
    echo $action;
    ?> </li>
<?php }?>

使用

strpos
可能会导致错误匹配。例如,如果
$action
TV
并且
$dservices
包含
HDTV

© www.soinside.com 2019 - 2024. All rights reserved.