skip to Main Content

In WooCommerce I can get the variaation name with:

$variation_obj = wc_get_product($variation['variation_id']);                                    
variation_name = $variation_obj->get_name();

This gives me an output with the following pattern: ” – ” but I just need the Variation attribute output. Examples are:
“Refresh Spray – 250 ml”
“Refresh Spray – 500 ml”
“Refresh Spray – 1 l”

How can I remove the ” – ” and everything in front of it?

3

Answers


  1. There are various different methods for doing this kind of thing but my trick is the code below.

    <?php
    
    $var = "blahblahblah - hello"; // put here your variable containing the "-"
    $var = explode("-", $var); // cuts the string into pieces at the "-" and removes the "-"
    $var = $var[0]; // grabs the part before the "-"
    $var = $var."-"; // adds the "-" again, remove this part if you don't want the "-"
    
    echo($var);
    
    ?>
    

    this should do exactly what you want.

    Login or Signup to reply.
  2. You can search for the last occurrence and get the string after that:

    $name = substr($variation_name, strrpos($variation_name, '-'));
    

    and when you want to remove any whitespaces use trim afterwards:

    $name = trim($name);
    
    Login or Signup to reply.
  3. If you want to remove everything before “-” including it:

    $str_after = preg_replace("#.+s?-#","",$variation_name);
    

    But if you want to remove everything after including the “-“:

    $str_before = preg_replace("#-s?.+#","",$variation_name);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search