繁体   English   中英

用两个分隔符拆分字符串并保持顺序和分隔符

[英]split string with two delimiters and keep order and delimiter

我想用两个分隔符拆分文本并保留分隔符和顺序:

例如:

$text = "* aaa aaa - bbb bbb - ccc * ddd * eee";

'*' 表示负值

'-' 表示正值

我想在输出中显示:

1 - Negative: aaa aaa
2 - Positive: bbb bbb
3 - Positive: ccc
4 - Negative: ddd
5 - Negative: eee

我使用explode()来拆分:

$negatives = explode("*",$text);
$positives= explode("-",$text);

但问题是,当我使用 expand() 时,我无法排序。

问题是:如何用两个分隔符分割文本并检测分隔符和顺序?

我想你可以先使用 preg_replace() 来“格式化”字符串,然后插入一些在其他地方没有使用过的项目分隔符,使用起来很安全? 在这种情况下,我使用 \\t 作为插入的分隔符。

$formatted_text = preg_replace('/ ?([-*]) /', "\t$1", $text);
$items_with_one_empty_in_front = explode("\t", $formatted_text);
var_dump($items_with_one_empty_in_front);

array(6) {
  [0]=>
    string(0) ""
  [1]=>
    string(4) "*aaa"
  [2]=>
    string(4) "-bbb"
  [3]=>
    string(4) "-ccc"
  [4]=>
    string(4) "*ddd"
  [5]=>
    string(4) "*eee"
}

然后你可以这样做:

foreach(array_slice($items_with_one_empty_in_front, 1) as $i => $item) {
  if ($item[0] == '*') {
    echo "$i - Negative: ".substr($item, 1);
  }
  else if ($item[0] == '-') {
    echo "$i - Positive: ".substr($item, 1);
  }
}

版本 2:

$parts = explode(" ", $text);
$opwords = [
  '*' => 'Negative',
  '-' => 'Positive'
];
$i = 1;
while($parts) {
  $op   = array_shift($parts);
  $term = array_shift($parts);
  echo $i++ . " - " . $opwords[$op] . ": ". $term . "\n";
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM