5

I have several strings similar to the following: ORG-000012 – Name of variation – Quantity: 12 Pack – $14.95

I need to remove all characters before the second hyphen and after the last hyphen with php. For example, the string above needs to return as: Name of variation – Quantity: 12 Pack

I have tried to use strpos and substr but I can't seem to get the correct setup. Please help!

Christy
  • 191
  • 1
  • 4
  • 12

3 Answers3

3

You can find the position of the first occurrence of - char using strpos and find the position of the last occurrence ot it using strrpos:

$s = 'ORG-000012 - Name of variation - Quantity: 12 Pack - $14.95';
$sub = substr($s,strpos($s, '-')+1, strrpos($s, '-')-strlen($s));
print $sub; // or print trim($sub) to remove the whitespaces

What it does is, it will print a substrinig of $s starting from one character after the first occurrence of - character, and omitting characters from last occurrence of - by passing a negative value (difference of total length of the string and position of last occurrence of - character) as length to substr.

Please note, this will print the space character before the last - as well, so you might want to trim the result as well.

Nima
  • 3,309
  • 6
  • 27
  • 44
1

Just use explode(), splitting by . Then, get the second and third elements:

<?php
$description = "ORG-000012 – Name of variation – Quantity: 12 Pack – $14.95";
$descriptionArray = explode(" – ", $description);
$finalDescription = $descriptionArray[1]." – ".$descriptionArray[2];
var_dump($finalDescription); // string(39) "Name of variation – Quantity: 12 Pack"

Demo

Or, if the number of elements in between is variable, array_shift() and array_pop() the array to remove the first and last elements:

<?php
$description = "ORG-000012 – Name of variation – Quantity: 12 Pack – $14.95";
$descriptionArray = explode(" – ", $description);
array_pop($descriptionArray);
array_shift($descriptionArray);
var_dump($descriptionArray);

Demo

ishegg
  • 9,685
  • 3
  • 16
  • 31
  • Thank you! This helped me get to where I needed to be. The Demo's were a nice touch. Much appreciated! – Christy Sep 21 '17 at 19:24
0

Is possible with a reg expr, try with:

preg_match(
    '/(?<=\s–\s)(.*)(?:\s–\s)[^\s]+$/',
    'ORG-000012 – Name of variation – Quantity: 12 Pack – $14.95',
    $matches
);
echo $matches[1]; //Name of variation – Quantity: 12 Pack 
kip
  • 1,120
  • 7
  • 11