在PHP中输出整数之间的文本

时间:2013-06-19 19:39:24

标签: php arrays string

我有一串文字,我想在整数之间分成多个字符串。

$string = "1 This is the first sentence. 2 This is the second sentence, 3 hello world!";

我想将其输出到:

$string1 = "1 This is the first sentence.";
$string2 = "2 This is the second sentence,";
$stirng3 = "3 hello world!";

或者数组也很好

1 个答案:

答案 0 :(得分:6)

这适用于您的用例,但可能会破坏。

preg_match_all("/[0-9]+ [^0-9]+/", $string, $matches);

将在$matches

中为您提供帮助
array(1) {
  [0]=>
  array(3) {
    [0]=>
    string(30) "1 This is the first sentence. "
    [1]=>
    string(31) "2 This is the second sentence, "
    [2]=>
    string(14) "3 hello world!"
  }
}

您可以使用trim()来消除额外的空格。


如果您不需要整数,您可能也会对preg_split()感兴趣

preg_split("/[0-9]+/", $strings);

返回

array(4) {
  [0]=>
  string(0) ""
  [1]=>
  string(29) " This is the first sentence. "
  [2]=>
  string(30) " This is the second sentence, "
  [3]=>
  string(13) " hello world!"
}