public9nf
public9nf

Reputation: 1399

PHP-String remove everything before and including " - "

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?

Upvotes: 0

Views: 86

Answers (3)

Hardood
Hardood

Reputation: 523

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

Upvotes: 0

Bernhard
Bernhard

Reputation: 424

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

Upvotes: 2

Bluppie05
Bluppie05

Reputation: 123

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.

Upvotes: 0

Related Questions