Reputation: 4622
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.
Upvotes: 0
Views: 754
Reputation: 48041
The second call to strtok()
can isolate the desired substring.
Notice that the character mask on the second call includes a space so that the following value is effectively left trimmed.
Code: (Demo)
$string = 'Acme Building Company - BZ-INTERNAL 1';
strtok($string, '-');
var_export(strtok('- '));
// 'BZ'
Upvotes: 0
Reputation: 42
<?php preg_match("/(.*)-(.*)-(.*)/", $input_line, $output_array); echo trim($output_array[2]);?>
or
<?php preg_match("/(.*) - (.*)-(.*)/", $input_line, $output_array); echo $output_array[2];?>
Upvotes: 0
Reputation: 2877
Using a regular expression will do this quite nicely.
$match = null;
if (preg_match('/- (.*?)-/', $string, $matches)) {
$match = $matches[1];
}
Upvotes: 0
Reputation: 2561
@user982124 if your string format will be the same so yes you can explode() it and at the 1th index you will get your characters like:
<?php
$string1 = 'Acme Building Company - BZ-INTERNAL 1';
$string2 = 'Acme Building Company - TRP-SHOP-1';
$string3 = 'Acme Building Company - ZJG-INTERNAL 2';
$strArr1 = explode("-", $string1);
echo trim($strArr1[1])."<br>";
$strArr2 = explode("-", $string2);
echo trim($strArr2[1])."<br>";
$strArr3 = explode("-", $string3);
echo trim($strArr3[1])."<br>";
Upvotes: -1
Reputation: 1144
Im keen to wait and see how other people would approach this question. But if you can guarantee the string will always be formatted the way you have shown I would personally try:
$exploded = explode('-', $string);
$intials = trim($exploded[1]);
Upvotes: 0
Reputation: 6254
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.
Upvotes: 2