用字符串/ 3个部分剪切字符串

时间:2017-12-30 03:05:14

标签: php string split cut

我不想像这样剪掉我的字符串



a = "dog [hidden] cat [/hidden] fox"


$1 = "dog ";
$2 = " fox";
$hidden = " cat ";




我正在寻找一种顺利的方式来做到这一点!谢谢你们!

2 个答案:

答案 0 :(得分:0)

这真的很有趣。

首先,我们需要将字符串分解为有意义的部分:

php > var_dump(preg_split('/(\[hidden\])|(\[\/hidden\])/', 'dog [hidden] cat [/hidden] fox', -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY));
array(5) {
  [0]=>
  string(4) "dog "
  [1]=>
  string(8) "[hidden]"
  [2]=>
  string(5) " cat "
  [3]=>
  string(9) "[/hidden]"
  [4]=>
  string(4) " fox"
}

从这里开始,我们想要找到[hidden]开始的时间和结束的位置。这将通过搜索数组来查找索引来完成。但是,由于示例中只有隐藏标记而没有其他标记,因此我们知道[hidden]之后的值为$hidden,其前面的所有内容都为$before,索引为{ {1}}加2就是它之后的所有内容(hidden)。

$after

总而言之,你得到了这个:

$hidden_start_index = array_search ("[hidden]", $my_array);
$before = my_array[hidden_start_index-1];
$after = my_array[hidden_start_index+2];
$hidden = my_array[hidden_start_index+1];

你可能想要更复杂的东西,但逻辑的基础在这里。

答案 1 :(得分:0)

以下是我建议你的解决方案:

<?PHP

$text = "dog [hidden] cat [/hidden] fox";

// find the "hidden" words between the tags
preg_match_all("/\[hidden\] ?(.*?) ?\[\/hidden\]/", $text, $hidden);
print_r($hidden[1]);

// find the "visible" words using a diff
$all = array_map("trim",preg_split("/\[\/?hidden\]/", $text));
$visible = array_values(array_diff($all, $hidden[1]));
print_r($visible);

?>

输出:

HIDDEN WORDS:

Array
(
    [0] => cat
)

VISIBLE WORDS:

Array
(
    [0] => dog
    [1] => fox
)

您可以尝试访问this link的演示。

相关问题