Reputation: 253
Alright, I'm getting data from an external API that scrapes market-data of the Steam market.
Now I'm getting a string as follows,
Desert Eagle | Night (Field-Tested)
Then what I'm trying to do is get what type of weapon it is, what it's name is and what wear it is.
This is what I'm trying to get it to put out,
Desert Eagle
Night
Field-Tested
or FT
This is the code I used to do this,
$item_wear = preg_replace('/^.*(\(.*\)).*$/', '$1', $item); //(Field-Tested)
$item_wear_short = preg_replace("/(?![A-Z])./", "", $item_wear); //FT
$exp_item_version = explode(" | ", str_replace($item_wear,"", $item)); //Array of Desert Eagle and Night
$item_version = $exp_item_version[0]; //Desert Eagle
$item_name = $exp_item_version[1]; //Night
That's basically what I've done, but now if there's an item named like,
Chroma Case Key
It'll do all sorts of stuff, while with strings that don't have a wear or anything I'd just like it so the $item_name
is Chroma Case Key
and the other strings just return empty, any proper way of doing this? also the code I used looks pretty messy in my opinion, anything I could change?
Upvotes: 0
Views: 77
Reputation: 763
For the given case you can use pre_split()
with three delimiters.
$str="Desert Eagle | Night (Field-Tested)";
$data=preg_split( "/[\(\)|]/", $str );
var_dump($data);
You can extend it further according to your requirements. Here you'll find more explanation if you need.
Upvotes: 1
Reputation: 6540
First you should check wether there is a |, that will tell you wether there is a version & wear in the string, if not, assume the string = item name.
$item_name = '';
$item_version = '';
$item_wear = '';
$item_wear_short = '';
$split = explode('|',$item);
$item_name = $split[0];
if(count($split)==2){ // Has version and possibly wear
$version_and_wear = $split[1];
// check for wear
$wear_index = strpos($version_and_wear, '(');
if($wear_index!==false){ // contains wear
$wear_end_index = strpos($version_and_wear, ')',$wear_index);
if($wear_end_index!==false){
$item_wear = substr($version_and_wear,$wear_index+1,$wear_end_index-$wear_index-1); // extract wear
$item_wear_short = preg_replace("/(?![A-Z])./", "", $item_wear); //FT
$version_and_wear = substr($version_and_wear,0,$wear_index); // remove wear from item string
}
}
$item_version = trim($version_and_wear); //remove whitespaces at the beginning and end of the string
}
Upvotes: 2