我试图查看一个数组是否包含一组特定的字符串。在我的具体情况下,我有一个包含客户地址的数组。我试图查看每个地址是否都是邮政信箱。如果所有地址都是邮政信箱,我想打印一条错误信息。
这就是我现在所拥有的。
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 :(得分: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