简体   繁体   中英

split string with two delimiters and keep order and delimiter

I want to split text with two delimiters and keep delimiter and order:

for example:

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

'*' means negative value

'-' means positive value

I want to show in output:

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

I use explode() to split :

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

But the problem is that , when I use explode() I can not sort.

question is that: How can I split text with two delimiters and detect delimiter and order?

I guess you could use preg_replace() to kind of "format" the string first, and insert some item delimiter that's not used elsewhere and so safe to use? In this case I'm using \\t as the inserted delimiter.

$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"
}

You could then do like this:

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);
  }
}

Version 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";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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