如何从字符串右侧删除货币缩写?

时间:2017-12-12 10:30:21

标签: php replace substring trailing

我有一个像这样的示例数组:

[
  "BTCUSD",
  "DASHBTC",
  "DOGEUSD",
  "LTCBTC",
  "LTCUSD",
  "SCBTC",
  "STEEMBTC",
  "WAVESBTC",
  "SNGLSBTC",
  "1STBTC",
  "DASHUSD",
  "BQXETH",
  "PTOYETH",
  "XAURETH",
  "BTCUSDT"
]

如何为每个字符串只获取一种货币?我不能使用explode,因为没有单个/静态分隔符。我无法使用substr()strpos(),因为子字符串会有所不同。

那么如何拆分?

更新

这是我的预期输出

[
   "BTC",
   "DASH",
   "DOGE",
   "LTC",
   "LTC",
   "SC",
   "STEEM",
   "WAVES",
   "SNGLS",
   "1ST",
   "DASH",
   "BQX",
   "PTOY",
   "XAUR",
   "BTC"
]

3 个答案:

答案 0 :(得分:1)

您需要有一个预期货币的数组,然后对其进行过滤。

以下是一个快速而肮脏的解决方案:https://3v4l.org/6mMbN或使用递归函数调用:https://3v4l.org/mhjBD

<?php

$currencies = [
    'USD',
    'BTC',
    'DASH',
    'LTC',
    'SC',
    'STEEM',
    'WAVES',
    'SNGLS',
    '1ST',
    'BQX',
    'ETH',
    'PTOY',
    'XAUR',
    ];

$input = [
  "BTCUSD",
  "DASHBTC",
  "DOGEUSD",
  "LTCBTC",
  "LTCUSD",
  "SCBTC",
  "STEEMBTC",
  "WAVESBTC",
  "SNGLSBTC",
  "1STBTC",
  "DASHUSD",
  "BQXETH",
  "PTOYETH",
  "XAURETH",
  "BTCUSDT",
];

$output=[];
foreach($input as $doubleCurrency){
    foreach($currencies as $currency){
        $pattern = '/^'.$currency. '/';
        preg_match($pattern, $doubleCurrency, $matches);
        if(array_key_exists(0, $matches)){
            $output[]=$matches[0];
        }
    }
}

var_dump($output);

答案 1 :(得分:1)

您总是修剪字符串的右侧,只需将preg_replace()与字符串锚点结束即可。不需要查找数组。这样做并不容易:

代码:(Demo

$input=[
  "BTCUSD",
  "DASHBTC",
  "DOGEUSD",
  "LTCBTC",
  "LTCUSD",
  "SCBTC",
  "STEEMBTC",
  "WAVESBTC",
  "SNGLSBTC",
  "1STBTC",
  "DASHUSD",
  "BQXETH",
  "PTOYETH",
  "XAURETH",
  "BTCUSDT"
];

var_export(preg_replace('/USDT$|USD$|ETH$|BTC$/','',$input));

输出:

array (
  0 => 'BTC',
  1 => 'DASH',
  2 => 'DOGE',
  3 => 'LTC',
  4 => 'LTC',
  5 => 'SC',
  6 => 'STEEM',
  7 => 'WAVES',
  8 => 'SNGLS',
  9 => '1ST',
  10 => 'DASH',
  11 => 'BQX',
  12 => 'PTOY',
  13 => 'XAUR',
  14 => 'BTC',
)

(如果你不介意语法,可以压缩模式。/USDT?$|ETH$|BTC$/更快一点。)

答案 2 :(得分:0)

这是一个类似于Edwin的答案,但可能更快 我使用str_replace在货币之间创建一个空格然后我循环新数组并删除第一个空格后的任何内容。

例:
&#39; STEEMBTC&#39;成为STEEM BTC&#39;。
然后将其改为:&#39; STEEM&#39;。

可能更快的代码,因为它循环较少而且不使用正则表达式。

$currencies = [
  'USD',
  'BTC',
  'DASH',
  'LTC',
  'SC',
  'STEEM',
  'WAVES',
  'SNGLS',
  '1ST',
  'BQX',
  'ETH',
  'PTOY',
  'XAUR',
  'DOGE'
];

$repl = [
  'USD ',
  'BTC ',
  'DASH ',
  'LTC ',
  'SC ',
  'STEEM ',
  'WAVES ',
  'SNGLS ',
  '1ST ',
  'BQX ',
  'ETH ',
  'PTOY ',
  'XAUR ',
  'DOGE '
];

$input = [
  "BTCUSD",
  "DASHBTC",
  "DOGEUSD",
  "LTCBTC",
  "LTCUSD",
  "SCBTC",
  "STEEMBTC",
  "WAVESBTC",
  "SNGLSBTC",
  "1STBTC",
  "DASHUSD",
  "BQXETH",
  "PTOYETH",
  "XAURETH",
  "BTCUSDT",
];

$new = str_replace($currencies, $repl, $input);
Foreach($new as &$item){
    $item = substr($item, 0, strpos($item, " "));
}

Var_dump($new);

https://3v4l.org/QDMjS