拆分字符串时保持分隔符

时间:2017-07-25 17:01:51

标签: php regex

使用preg_split分割字符串时,下面的代码不会保留分隔符。

$feature_description = "- 1.Read/Write speed performance is based on internal testing.- 2.TBW (terabytes written) values calculated capacity.";


preg_split('/(- [0-9].)/',$feature_description,NULL,PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

现在的输出是:

    [0] => - 1.
    [1] => Read/Write speed performance is based on internal testing.
    [2] => - 2.
    [3] => TBW (terabytes written) values calculated capacity.

但我希望输出为:

    [1] => - 1.Read/Write speed performance is based on internal testing.
    [2] => - 2.TBW (terabytes written) values calculated capacity.

3 个答案:

答案 0 :(得分:1)

使用 Represent the state-action value as a normalized vector (or as a one-hot vector representing the state and action) 1. Input layer : Size= number of inputs 2. `n` hidden layers with `m` neurons 3. Output layer: single output neuron Sigmoid activation function. Update weights using gradient descent as per the * semi-gradient Sarsa algorithm*. 使用这个基于前瞻性的正则表达式而不是分裂你应该使用preg_match_all进行匹配:

-\h+\d+.+?(?=-\h+\d+|\z)

convergence even with non-linear function approximators

RegEx分手:

  • -\h+\d+:匹配连字符后跟1 +水平空格和1+位数
  • .+?:匹配零个或多个任何字符(懒惰)
  • (?=-\h+\d+|\z):预见断言我们有连字符后跟1 +水平空格和1+位数或字符串结尾

答案 1 :(得分:1)

以前瞻眼分裂:

$feature_description = "- 1.Read/Write speed performance is based on internal testing.- 2.TBW (terabytes written) values calculated capacity.";
$res=preg_split('/(?=- [0-9]+\.)/',$feature_description,NULL, PREG_SPLIT_NO_EMPTY);
print_r($res);

结果:

Array
(
    [0] => - 1.Read/Write speed performance is based on internal testing.
    [1] => - 2.TBW (terabytes written) values calculated capacity.
)

请参阅PHP demo

请注意,您不再需要PREG_SPLIT_DELIM_CAPTURE,因为正则表达式现在没有捕获组。

请注意,您需要转义一个点以匹配文字点。

模式详细信息(?=- [0-9]+\.)是与-之前的位置匹配的正向前瞻,空格,1位或多位数,.

您可以像

那样增强正则表达式
'/\s*(?=-\h[0-9]+\.)/' 

以便删除匹配项之间的任何空格(\s*)并匹配-和数字之间的任何水平空格。

答案 2 :(得分:0)

为什么你不能这样做:

$feature_description = "- 1.Read/Write speed performance is based on internal testing.- 2.TBW (terabytes written) values calculated capacity.";

$feature_description_array = explode("-", $feature_description);//now we have an array broken up by the "-" delmiter

现在你应该拥有如下数组:

Array
(
    [0] => 1.Read/Write speed performance is based on internal testing.
    [1] => 2.TBW (terabytes written) values calculated capacity.
)

打印时,您可以只添加缺少的" - "与

echo "- ". Array[0];