在每个非字母数字字符后插入空格

时间:2014-09-15 23:22:42

标签: php arrays explode alphanumeric non-alphanumeric

我试图在字符串中的每个非字母数字字符之前和之后插入空格,例如用户输入的字符串(good + bad)* nice,我想让它看起来像(好+坏)*不错。我想这样做的原因是因为我想将它们放在数组中,看起来像这样;

  $arr[0] = "(";
  $arr[1] = "good”;
  $arr[2] = "+”;
  $arr[3] = "bad";
  $arr[4] = ")";
  $arr[5] = "*";
  $arr[6] = "+";

5 个答案:

答案 0 :(得分:0)

尚未对此进行测试,但您可以使用正则表达式来完成此操作。

s/\W/$1 /g

答案 1 :(得分:0)

我相信您可以使用preg_replace来实现这一目标。例如:

$string = "(good+bad)";
echo preg_replace('/\W+/', ' $0 ', $string);

答案 2 :(得分:0)

您可以使用preg_replace(),例如:

echo preg_replace('/[^a-zA-Z0-9_ ]/', ' $0 ', '(good+bad)*nice');

答案 3 :(得分:0)

您可以使用preg_split在一行中完成此操作。

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

结果:

array(
  0 => "("
  1 => "good"
  2 => "+"
  3 => "bad"
  4 => ")"
  5 => "*"
  6 => "nice"
}

答案 4 :(得分:0)

这类似于PHP - iterate on string characters

基本上使用str_split和/或preg_Split

取自preg_split页面(稍加修改:

<?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";
?>

这只是一个可以完成工作的快速模型。 (删除生产代码的转储/打印)