Search code examples
phpsubstring

PHP - Parse out characters from string


I'm working with some strings that appear in the following formats:

 $string = 'Acme Building Company - BZ-INTERNAL 1';
 $string = 'Acme Building Company - TRP-SHOP-1';
 $string = 'Acme Building Company - ZJG-INTERNAL 2';

I now need to get to the characters in the middle of these strings and parse them out, so in the above examples I would end up with the following:

  BZ
  TRP
  ZJG

I'm looking for the most dynamic approach so I don't have to hardcode any substitution strings but haven't been able to come up with anything so far.


Solution

  • Use explode(); PHP function like so:

    <?php
    $string = 'Acme Building Company - BZ-INTERNAL 1';
    $tmp = explode('-', $string);
    $middle = trim($tmp[1]);
    echo $middle;
    

    The output of the above code segment will be: BZ

    The syntax goes explode(DELIMITER, THE_STRING); Which returns an array.

    So when we explode the given string BZ cones in the array index 1. You can use the same approach for all your strings, maybe in a loop.