-1

Am trying to insert space before and after every non alphanumeric character in the string, for example string like (good+bad)*nice which will be entered by user, I want to make it look like ( good + bad ) * nice. The reason i want to do this, is because i want to put them in array which is going to look like this;

  $arr[0] = "(";
  $arr[1] = "good”;
  $arr[2] = "+”;
  $arr[3] = "bad";
  $arr[4] = ")";
  $arr[5] = "*";
  $arr[6] = "+";
  • i think if you explained the big picture a better rapport could be suggested –  Sep 15 '14 at 23:27
  • Are you trying to parse a mathematical expression by splitting on spaces, so that you can convert it to a stack for evaluation? Look at [ircmaxell's answer](http://stackoverflow.com/questions/12692727/how-to-make-a-calculator-in-php) here.... no spaces needed – Mark Baker Sep 15 '14 at 23:30

4 Answers4

0

You can use preg_split to accomplish that in one line.

$result = preg_split('/(\w+|\W)/', '(good+bad)*nice', -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);

result:

array(
  0 => "("
  1 => "good"
  2 => "+"
  3 => "bad"
  4 => ")"
  5 => "*"
  6 => "nice"
}
Yaroslav
  • 2,338
  • 26
  • 37
-1

Haven't tested this, but you might be able to use a regex to accomplish this.

s/\W/$1 /g
Nick
  • 3,096
  • 3
  • 20
  • 25
-1

I believe You can use preg_replace to achieve this. For example:

$string = "(good+bad)";
echo preg_replace('/\W+/', ' $0 ', $string);
cdr
  • 131
  • 1
  • 4
-1

This is similar to PHP - iterate on string characters

Basically use str_split and/or preg_Split

Taken from the preg_split page (And slightly modified:

<?php
$str = "(alpah+beta)*ga/6";
$keywords = preg_split("/[\/\(\)\*\&\^\%\$\#\@\!\_\{\}\:\"\+\\\]/", "$str");
print_r($keywords);
// now we replace the keywords with itself + a space on the left and right.
$count = count($keywords);

for ($i = 0; $i < $count; $i++) {
    if ( $keywords[$i] == '') {
        unset($keywords[$i]);
    }

}
var_dump($keywords);
foreach ($keywords as &$key) {
     $str = preg_replace("/$key/", " $key ", "$str");
}
echo "Finally: $str";
?>

This was just a quick mockup of something that will do the job. (Remove the dumps/prints for production code)

Community
  • 1
  • 1
ticoombs
  • 333
  • 2
  • 4