drfu29983 2016-03-21 22:46
浏览 31
已采纳

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

I am trying to see if an array contains a specific set of strings. In my specific situation, I have an array that contains customer addresses. I am trying to see if every address is a PO Box or not. I want to print an error message if all of their addresses are PO Boxes.

This is what I currently have.

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
  • 写回答

1条回答 默认 最新

  • douduocuima61392 2016-03-21 22:56
    关注

    Here is how I would approach it:

    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;
    }
    

    Your code was pretty close to working already, you mainly just needed the preg_match function to check against a regex pattern.


    Here's a more terse option:

    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);
        }));
    }
    

    See here for an example: https://3v4l.org/JQQpA

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能