php strpos函数的多个输入?

x123

我尝试创建一个脚本来自动将品牌添加到我的产品中,但我需要一个解决方案来检查 100 多个品牌而不是一个:/所以在这种情况下我有“$brand = 'Ray Ban';” 但我需要将其替换为“$brand = 'Ray Ban, Adidas, Nike';” 有谁知道我该如何处理?

  function atkp_product_updated_callback2($product_id) {
        require_once  ATKP_PLUGIN_DIR.'/includes/atkp_product.php';
        /* Get Woocommerce Product ID*/
        $woo_product = atkp_product::get_woo_product($product_id);
        $woocommerce_product_id = $woo_product->ID;

        $name = ATKPTools::get_post_setting( $product_id, ATKP_PRODUCT_POSTTYPE.'_title');
      /* Get Brand List */
        $brand = 'Ray Ban';
      /* Check if brandname in product name */
        $brandchecker = strpos($name, $brand);
        if ($brandchecker === false) {
            /* if try another */
        } else {
            /* if true add to brand*/
             ATKPTools::check_taxonomy($woocommerce_product_id, 'store', $brand); /* Add to the Woocommerce Store Taxonmy */
        }
    }
add_action('atkp_product_updated', 'atkp_product_updated_callback2');
杰夫

使用preg_match_all()和正则表达式中的 or 运算符,如果您有$brands这样的数组,您可以搜索多个针

<?php
$brands = ["Ray Ban", "Adidas", "Mercedes"];

function hasBrands($brands, $heystack) {
   $regex = '('.implode('|', $brands).')';
   $success = preg_match_all($regex, $heystack, $matches);
    //var_dump($success);
   return $success;
}

echo hasBrands($brands, "Lorem Ray Ban and Adidas but not BMW") . "<br>";
echo hasBrands($brands, "but not BMW") . "<br>";
echo hasBrands($brands, "Adidas or Puma?") . "<br>";

// output:
// 2
// 0
// 1

如果您需要匹配的品牌,只需从函数中返回 $matches(如果没有找到,则返回一个空数组):

function getBrands($brands, $heystack) {
   $regex = '('.implode('|', $brands).')';
   $success = preg_match_all($regex, $heystack, $matches);
   return $success ? $matches[0] : [];
}

var_dump(getBrands($brands, "Lorem Ray Ban and Mercedes are in this string"));

// output:
array(2) {
  [0]=>
  string(7) "Ray Ban"
  [1]=>
  string(8) "Mercedes"
}

附录
如果您只想要第一个匹配项,请通过 [0] 从 getBrands 返回的数组中访问它。您应该首先检查是否确实找到了一个项目。

$foundBrands = getBrands($brands, "Lorem Adidas Mercedes BMW");
if(!empty($foundBrands)) {
    $firstBrand = $foundBrands[0];
} else {
    $firstBrand = null;
    echo "no brand found!";
}

echo $firstBrand; // Adidas

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章