2016-03-21 71 views
0

我想查看数组是否包含特定的一组字符串。在我的具体情况中,我有一个包含客户地址的数组。我试图看看每个地址是否是邮政信箱。如果所有地址都是邮政信箱,我想打印一条错误消息。PHP请参阅如果数组中包含所有值包含字符串

这是我现在拥有的。

public function checkPhysicalAddressOnFile(){ 
    $customer = Mage::getSingleton('customer/session')->getCustomer(); 
    foreach ($customer->getAddress() as $address) { 
     if stripos($address, '[p.o. box|p.o box|po box|po. box|pobox|post office box]') == false { 
      return false 
+0

我将其标记为最佳答案!谢谢! – djames

回答

0

这里是我会怎么处理它:

public function checkPhysicalAddressOnFile(){ 
    $addresses = Mage::getSingleton('customer/session')->getCustomer()->getAddresses(); 

    foreach($addresses AS $address) { 
     if(!preg_match("/p\.o\. box|p\.o box|po box|po\. box|pobox|post office box/i", $address)) { 
      // We found an address that is NOT a PO Box! 
      return true; 
     } 
    } 

    // Apparently all addresses were PO Box addresses, or else we wouldn't be here. 
    return false; 
} 

你的代码是非常接近已经工作,你主要是刚需的preg_match功能检查对正则表达式模式。


这里有一个更简洁的选择:

public function checkPhysicalAddressOnFile() { 
    return (bool) count(array_filter(Mage::getSingleton('customer/session')->getCustomer()->getAddresses(), function($address) { 
     return !preg_match("/p\.o\. box|p\.o box|po box|po\. box|pobox|post office box/i", $address); 
    })); 
} 

在这里看到一个例子:https://3v4l.org/JQQpA