You are here:  » Explode Filter, keeping everything before last instance


Explode Filter, keeping everything before last instance

Submitted by techdesigns on Mon, 2020-02-17 17:30 in

Hi

I've setup a filter which explodes on certain characters " - ", keeping the part before those characters - is it possible to do this but just for the last instance of those characters?

i.e.

"Name Product Name - Black" > "Name Product Name"
"Product - Name 2 - Black" > "Product - Name 2" rather than "Product"

Thanks in advance

Joey

Submitted by support on Thu, 2020-02-20 15:06

Hi Joey,

Here's code for an "Explode Implode" filter that will do this - add to includes/filter.php before the closing PHP tag:

  /*************************************************/
  /* Explode Implode */
  /*************************************************/
  $filter_names["explodeImplode"] = "Explode Implode";
  function filter_explodeImplodeConfigure($filter_data)
  {
    widget_textBox("Explode character or string","text",TRUE,$filter_data["text"],"",3);
    widget_textBox("Remove","remove",TRUE,$filter_data["remove"],"",2);
  }
  function filter_explodeImplodeValidate($filter_data)
  {
    if (!$filter_data["text"])
    {
      widget_errorSet("text","required field");
    }
    if (!is_numeric($filter_data["remove"]))
    {
      widget_errorSet("remove","required numeric field");
    }
  }
  function filter_explodeImplodeExec($filter_data,$text)
  {
    $parts = explode($filter_data["text"],$text);
    $remove = intval($filter_data["remove"]);
    $fn = (($remove < 0)?"array_pop":"array_shift");
    for($i = 1;$i <= abs($remove); $i++) $fn($parts);
    return implode($filter_data["text"],$parts);
  }

Remove can be positive (remove first n items) or negative (remove last n items) so in this example, use " - " (without the quotes but include the spaces) and -1 as the Remove value and that should do the trick...

Cheers,
David.
--
PriceTapestry.com