PHP 查看数组中的所有值是否都包含字符串


PHP See If All Values In Array Contain String

我正在尝试查看数组是否包含一组特定的字符串。在我的特定情况下,我有一个包含客户地址的数组。我正在尝试查看每个地址是否都是邮政信箱。如果他们的所有地址都是邮政信箱,我想打印错误消息。

这就是我目前拥有的。

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

以下是我的做法:

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