phpstringsubstrstrpos

Returning a string after the second occurrence of a character and before the last occurrence of the same character with php


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!


Solution

  • 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